<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="maintenanceType" label-position="top">-->
<!--        <el-select v-model="queryParams.maintenanceType" placeholder="请选择检修类型" clearable>-->
<!--          <el-option-->
<!--              v-for="dict in gxt_maintenance_type"-->
<!--              :key="dict.value"-->
<!--              :label="dict.label"-->
<!--              :value="dict.value"-->
<!--          />-->
<!--        </el-select>-->
<!--      </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="故障代码" prop="faultCode" label-position="top">
        <el-input
          v-model="queryParams.faultCode"
          placeholder="请输入故障代码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
    </el-form>
    <div style="float: right;">
      <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
    </div>
    <!-- 操作按钮区域 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['gxt:repairOrder:add']"
        >新建工单</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="info"
            icon="Upload"
            @click="handleImport"
            v-hasPermi="['gxt:repairOrder:import']"
        >导入维修工单</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="info"
            icon="Upload"
            @click="handleImportMis"
            v-hasPermi="['gxt:repairOrder:importMis']"
        >导入MIS工单</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            icon="Download"
            @click="handleExport"
            v-hasPermi="['gxt:repairOrder:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 工单列表 -->
    <el-table
        v-loading="loading"
        :data="repairOrderList"
        @selection-change="handleSelectionChange"
        style="width: 100%"
        :max-height="tableHeight"
    >
      <el-table-column type="selection" width="55" align="center" fixed />
      <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="maintenanceType" min-width="100">-->
<!--        <template #default="scope">-->
<!--          <dict-tag :options="gxt_maintenance_type" :value="scope.row.maintenanceType" />-->
<!--        </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="faultCode" width="120" :show-overflow-tooltip="true">
        <template #default="scope">
          {{ scope.row.faultCode || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="发生时间" align="center" prop="occurTime" width="150" >
        <template #default="scope">
          <span>{{ scope.row.occurTime ? parseTime(scope.row.occurTime, '{y}-{m}-{d} {h}:{i}') : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="MIS工单编码" align="center" prop="misOrderNo"  width="150" :show-overflow-tooltip="true">
        <template #default="scope">
          {{ scope.row.misOrderNo || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="下发人" align="center" prop="assignUserName" width="100" >
        <template #default="scope">
          {{ scope.row.assignUserName || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="下发时间" align="center" prop="assignTime" width="150">
        <template #default="scope">
          <span>{{ scope.row.assignTime ? parseTime(scope.row.assignTime, '{y}-{m}-{d} {h}:{i}') : '-' }}</span>
        </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" prop="priorityType" min-width="100">
              <template #default="scope">
                <dict-tag :options="gxt_order_priority_type" :value="scope.row.priorityType" />
              </template>
            </el-table-column>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="250" fixed="right">
        <template #default="scope">
<!--          <el-button-->
<!--              v-if="scope.row.workOrderStatus === 'to_issue'"-->
<!--              type="primary"-->
<!--              link-->
<!--              @click="handleEdit(scope.row)"-->
<!--              v-hasPermi="['gxt:repairOrder:edit']"-->
<!--          ><i class="fa fa-edit"></i>编辑</el-button>-->
<!--          <el-button-->
<!--              v-if="scope.row.workOrderStatus === 'to_issue'"-->
<!--              type="primary"-->
<!--              link-->
<!--              @click="handleAssign(scope.row)"-->
<!--              v-hasPermi="['gxt:repairOrder:assign']"-->
<!--          ><i class="fa fa-user-plus"></i>下发</el-button>-->
          <el-button
              v-if="scope.row.workOrderStatus === 'to_issue'"
              type="primary"
              link
              @click="handleEdit(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 === 'assigned'"
              type="warning"
              link
              @click="handleRevoke(scope.row)"
              v-hasPermi="['gxt:repairOrder:revoke']"
          ><i class="fa fa-reply"></i>撤回</el-button>
          <el-button
              v-if="scope.row.workOrderStatus === 'suspended'"
              type="primary"
              link
              @click="handleResume(scope.row)"
              v-hasPermi="['gxt:repairOrder:resume']"
          ><i class="fa fa-play"></i>恢复</el-button>
          <el-button
              v-if="scope.row.workOrderStatus === 'to_finish'"
              type="danger"
              link
              @click="handleSuspend(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.acceptUserId == 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 === 'processing'"
                      type="warning"
                      link
                      @click="handlePause(scope.row)"
                    >暂停</el-button>-->
          <!--          <el-button
                      v-if="scope.row.workOrderStatus === 'processing'"
                      type="success"
                      link
                      @click="handleProcessDone(scope.row)"
                    >结束</el-button>-->
          <el-button
              v-if="scope.row.workOrderStatus === 'to_finish' && (scope.row.teamLeaderId == userStore.id || userStore.roles.includes('admin'))"
              type="success"
              link
              @click="handleFinalize(scope.row)"
              v-hasPermi="['gxt:repairOrder:finalize']"
          ><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:repairOrder:approve']"
          ><i class="fa fa-check-circle"></i>审批</el-button>
          <!--          <el-button
                      v-if="scope.row.workOrderStatus === 'paused' || scope.row.workOrderStatus === 'suspended'"
                      type="primary"
                      link
                      @click="handleResume(scope.row)"
                    >恢复</el-button>-->
<!--          <el-button-->
<!--              v-if="scope.row.workOrderStatus === 'completed' && !scope.row.score"-->
<!--              type="warning"-->
<!--              link-->
<!--              @click="handleRating(scope.row)"-->
<!--              v-hasPermi="['gxt:repairOrder:rating']"-->
<!--          ><i class="fa fa-star"></i>评分</el-button>-->
          <el-button
              v-if="scope.row.workOrderStatus === 'completed'"
              type="success"
              link
              @click="handleRestart(scope.row)"
              v-hasPermi="['gxt:repairOrder:restart']"
          ><i class="fa fa-refresh"></i>复运</el-button>
          <el-button
              type="info"
              link
              @click="handleView(scope.row)"
              v-hasPermi="['gxt:repairOrder:query']"
          ><i class="fa fa-eye"></i>查看</el-button>
          <el-button
              v-if="scope.row.workOrderStatus === 'to_issue'"
              type="danger"
              link
              @click="handleDelete(scope.row)"
              v-hasPermi="['gxt:repairOrder:remove']"
          ><i class="fa fa-trash"></i>删除</el-button>
          <el-button
              v-if="scope.row.workOrderStatus !== 'invalid'"
              type="danger"
              link
              @click="handleInvalidate(scope.row)"
              v-hasPermi="['gxt:repairOrder:invalidate']"
          ><i class="fa fa-ban"></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"
    />

    <!-- 新建/编辑工单对话框 -->
    <el-dialog :title="dialogTitle" v-model="openDialog" width="800px" append-to-body @close="cancel">
      <el-form ref="repairOrderRef" :model="form" :rules="rules" label-width="120px" label-position="top">
        <el-row>
          <el-col :span="12">
            <el-form-item label="工单编码" prop="workOrderProjectNo" >
              <el-input v-model="form.workOrderProjectNo" placeholder="请输入工单编码" :disabled="!!form.id" 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="form.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="form.gxtCenter" placeholder="请选择风机编号自动填充" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="场站" prop="pcsStationName">
              <el-input v-model="form.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="form.brand" placeholder="请选择风机编号自动填充" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="机型" prop="model">
              <el-input v-model="form.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="form.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="form.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="form.faultBarcode"
                  type="textarea"
                  placeholder="请输入故障信息"
                  maxlength="100"
                  show-word-limit
                  :rows="3"
              />
            </el-form-item>
          </el-col>
        </el-row>
<!--        <el-row>
          <el-col :span="24">
            <el-form-item label="故障描述" prop="faultDesc">
              <el-input
                  v-model="form.faultDesc"
                  type="textarea"
                  placeholder="请输入故障描述"
                  maxlength="500"
                  show-word-limit
                  :rows="3"
              />
            </el-form-item>
          </el-col>
        </el-row>-->
        <!-- <el-row>
          <el-col :span="24">
            <el-form-item label="图片">
                <image-upload :limit="10" v-model="form.workUrl" :fileSize="5"></image-upload>
            </el-form-item>
          </el-col>
        </el-row> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm" v-if="optType == 'add'">保 存</el-button>
          <el-button type="primary" @click="submitFormAndIssue" v-if="!form.workOrderStatus">保存并下发</el-button>
          <el-button type="primary" @click="submitFormAndIssue" v-if="optType == 'edit'">确认下发</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 下发对话框 -->
    <el-dialog title="下发" v-model="assignDialogVisible" width="800px" append-to-body @close="closeAssignDialog">
      <el-form ref="assignFormRef" :model="assignForm" label-width="120px" label-position="top">
        <el-row>
          <el-col :span="12">
            <el-form-item label="工单编码"><el-input v-model="assignForm.workOrderProjectNo" disabled /></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="风机编号"><el-input v-model="assignForm.pcsDeviceName" disabled /></el-form-item>
          </el-col>
          <!--          <el-col :span="12">
                      <el-form-item label="检修类型">
                        <dict-tag :options="gxt_maintenance_type" :value="assignForm.maintenanceType" />
                      </el-form-item>
                    </el-col>-->
          <el-col :span="12">
            <el-form-item label="工单状态">
              <el-select v-model="assignForm.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="assignForm.gxtCenter" disabled /></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="场站"><el-input v-model="assignForm.pcsStationName" disabled /></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌"><el-input v-model="assignForm.brand" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="故障代码"><el-input v-model="assignForm.faultCode" disabled /></el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="故障信息">
              <el-input
                v-model="assignForm.faultBarcode"
                type="textarea"
                placeholder="请输入故障信息"
                maxlength="100"
                show-word-limit
                :rows="3"
                disabled
            /></el-form-item>
          </el-col>
        </el-row>

        <!--        <el-form-item label="关联维保工单">
                  <el-select
                    v-model="assignForm.relatedOrderCode"
                    filterable
                    remote
                    reserve-keyword
                    placeholder="请输入关联维保工单编码"
                    :remote-method="searchWorkOrders"
                    :loading="workOrderSearchLoading"
                    @change="handleWorkOrderChange"
                  >
                    <el-option
                      v-for="item in workOrderOptions"
                      :key="item.id"
                      :label="item.workOrderProjectNo"
                      :value="item.workOrderProjectNo"
                      :data-content="item.content"
                    >
                      <span style="float: left">{{ item.workOrderProjectNo }}</span>
                      <span style="float: right; color: #8492a6; font-size: 13px">{{ item.content }}</span>
                    </el-option>
                  </el-select>
                </el-form-item>

                <el-form-item
                  v-if="assignForm.relatedOrderCode"
                  label="维保内容"
                  prop="relatedOrderContent">

                  <el-input
                    v-model="assignForm.relatedOrderContent"
                    type="textarea"
                    placeholder="请输入维保内容"
                    maxlength="500"
                    show-word-limit
                    :rows="3"
                    readonly
                  />
                </el-form-item>-->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeAssignDialog">取 消</el-button>
          <el-button type="primary" @click="submitAssign">确认下发</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 接单对话框 -->
    <el-dialog title="接单" v-model="acceptDialogVisible" width="800px" append-to-body @close="closeAcceptDialog">
      <el-form ref="acceptFormRef" :model="acceptForm" :rules="acceptRules" label-width="120px" label-position="top">
        <el-row>
          <el-col :span="12">
            <el-form-item label="工单编码"><el-input v-model="acceptForm.workOrderProjectNo" disabled /></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="风机编号"><el-input v-model="acceptForm.pcsDeviceName" disabled /></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工单状态">
              <el-select v-model="acceptForm.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="acceptForm.gxtCenter" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="场站"><el-input v-model="acceptForm.pcsStationName" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌"><el-input v-model="acceptForm.brand" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="故障代码"><el-input v-model="acceptForm.faultCode" disabled /></el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="故障信息">
              <el-input
                  v-model="acceptForm.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-select v-model="acceptForm.teamLeaderId" placeholder="请选择工作负责人" style="width: 100%" @change="(userId) => acceptForm.teamLeaderName = userList.find(u => u.userId === userId)?.nickName">-->
<!--                <el-option-->
<!--                    v-for="user in userList"-->
<!--                    :key="user.userId"-->
<!--                    :label="user.nickName"-->
<!--                    :value="user.userId"-->
<!--                />-->
<!--              </el-select>-->
              <el-input
                  v-model="acceptForm.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-name">{{ item.dept.deptName }}</span>
                </div>
              </div>
              <div class="quick-select-dropdown no-data" v-show="showTeamLeaderQuickSelect && quickTeamLeaderList.length === 0 && acceptForm.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="closeAcceptDialog">取 消</el-button>
          <el-button type="primary" @click="submitAccept">确认接单</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 挂起对话框 -->
    <el-dialog title="申请挂起工单" v-model="suspendDialogVisible" width="800px" append-to-body @close="closeSuspendDialog">
      <el-form ref="suspendFormRef" :model="suspendForm" :rules="suspendRules" label-width="120px" label-position="top">
        <el-alert type="warning" :closable="false" title="请选择挂起原因，提交后需等待班长审批。" show-icon />
        <el-row>
          <el-col :span="12">
            <el-form-item label="工单编码">
              <el-input v-model="suspendForm.workOrderProjectNo" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="风机编号">
              <el-input v-model="suspendForm.pcsDeviceName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="suspendForm.faultBarcode">
            <el-form-item label="故障信息">
              <el-input v-model="suspendForm.faultBarcode" type="textarea" :rows="3" disabled />
            </el-form-item>
          </el-col>
<!--            <el-form-item label="挂起原因" prop="suspendReason">
              <el-input
                  v-model="suspendForm.suspendReason"
                  type="textarea"
                  placeholder="请输入挂起原因"
                  maxlength="100"
                  show-word-limit
                  :rows="3"
              />
            </el-form-item>-->
          <el-col :span="12">
            <el-form-item label="挂起原因" prop="suspendReason">
              <el-select v-model="suspendForm.suspendReason" placeholder="请选择挂起原因" style="width: 100%">
                <el-option
                    v-for="dict in gxt_order_suspend_reason"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!--
                <el-form-item label="详细说明" prop="suspendDescription">
                  <el-input
                    v-model="suspendForm.suspendDescription"
                    type="textarea"
                    placeholder="请输入详细说明"
                    maxlength="100"
                    show-word-limit
                    :rows="3"
                  />
                </el-form-item>-->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeSuspendDialog">取 消</el-button>
          <el-button type="primary" @click="submitSuspend">提交申请</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 审批对话框 -->
    <el-dialog title="审批挂起申请" v-model="approveDialogVisible" width="800px" append-to-body @close="closeApproveDialog">
      <el-alert type="info" :closable="false" style="border-color: #a855f7; background-color: #f8f5ff; color: #6d28d9; height: 35px;">
        <template #default>
          <i class="fa fa-edit mr-2" style="color: #6d28d9;"> 请审批该工单的挂起申请，选择通过或驳回。</i>
        </template>
      </el-alert>
      <!-- 工单信息 -->
      <h3 class="text-sm font-medium text-gray-800 mb-3"></h3>
      <el-form ref="approveFormRef" :model="approveForm" :rules="approveRules" label-width="120px" label-position="top">
        <el-row>
          <el-col :span="12">
            <el-form-item label="工单编码"><el-input v-model="approveForm.workOrderProjectNo" disabled /></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="风机编号"><el-input v-model="approveForm.pcsDeviceName" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工单状态">
              <el-select v-model="approveForm.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="approveForm.gxtCenter" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="场站"><el-input v-model="approveForm.pcsStationName" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌"><el-input v-model="approveForm.brand" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="故障代码"><el-input v-model="approveForm.faultCode" disabled /> </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="故障信息">
              <el-input
                v-model="approveForm.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="approveForm.assignUserName" disabled /></el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="下发时间"><el-input v-model="approveForm.assignTime" disabled /></el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="接单人"><el-input v-model="approveForm.acceptUserName" disabled /> </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="接单时间"><el-input v-model="approveForm.acceptTime" disabled /> </el-form-item>-->
<!--          </el-col>-->
          <el-col :span="12">
            <el-form-item label="工作负责人"><el-input v-model="approveForm.teamLeaderName" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="挂起原因">
              <el-select v-model="approveForm.suspendReason" style="width: 100%" disabled>
                <el-option
                    v-for="dict in gxt_order_suspend_reason"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
<!--        <el-form-item label="审批决定" prop="approvalStatus">
          <el-radio-group v-model="approveForm.approvalStatus" @change="toggleRejectionReason">
            <el-radio label="approved">通过</el-radio>
            <el-radio label="rejected">驳回</el-radio>
          </el-radio-group>
        </el-form-item>-->
        <el-form-item label="审批意见" prop="rejectionReason">
          <el-input
              v-model="approveForm.rejectionReason"
              type="textarea"
              placeholder="请输入审批意见"
              maxlength="100"
              show-word-limit
              :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeApproveDialog">取 消</el-button>
          <el-button type="primary" @click="submitApprove('rejected')">驳 回</el-button>
          <el-button type="primary" @click="submitApprove('approved')">通 过</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 结单对话框 -->
    <el-dialog title="结单" v-model="finalizeDialogVisible" width="800px" append-to-body @close="closeFinalizeDialog">
      <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>
      <h4 class="text-sm font-medium text-gray-800 mb-3"></h4>
      <el-form ref="finalizeFormRef" :model="finalizeForm" :rules="finalizeRules" label-width="120px" label-position="top">
        <el-row>
          <el-col :span="12">
            <el-form-item label="工单编码"><el-input v-model="finalizeForm.workOrderProjectNo" disabled /></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="风机编号"><el-input v-model="finalizeForm.pcsDeviceName" disabled /></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工单状态">
              <el-select v-model="finalizeForm.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="finalizeForm.gxtCenter" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="场站"><el-input v-model="finalizeForm.pcsStationName" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌"><el-input v-model="finalizeForm.brand" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="故障代码"><el-input v-model="finalizeForm.faultCode" disabled /> </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="故障信息">
              <el-input
                v-model="finalizeForm.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="finalizeForm.assignUserName" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下发时间"><el-input v-model="finalizeForm.assignTime" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="接单人"><el-input v-model="finalizeForm.acceptUserName" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="接单时间"><el-input v-model="finalizeForm.acceptTime" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工作负责人"><el-input v-model="finalizeForm.teamLeaderName" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="维修方式" prop="repairMethod">
              <el-select
                v-model="finalizeForm.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>

          <!-- 正常维修时显示的字段 -->
          <template v-if="!finalizeForm.repairMethod || finalizeForm.repairMethod === '1'">
            <el-col :span="12">
              <el-form-item label="MIS工单编码" prop="misOrderNo">
                <el-input
                  v-model="finalizeForm.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 && form.misNo">
                  <div>未找到匹配的MIS工单</div>
                </div>
              </el-form-item>
            </el-col>
            <!-- MIS选择组件 -->
            <MisInfoSelectSingle :key="commonKey" v-model="misInfoSelectVisible" @onSelected="onMisInfoSelected" :pcsStationName="finalizeForm.pcsStationName" :pcsDeviceName="finalizeForm.pcsDeviceName"></MisInfoSelectSingle>
            <el-col :span="12">
              <el-form-item label="开始时间" prop="realStartTime">
                <el-date-picker
                    v-model="finalizeForm.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="finalizeForm.realEndTime"
                    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="workGroupMemberName">
                <el-input
                    v-model="finalizeForm.workGroupMemberName"
                    placeholder="请输入检修人员"
                    maxlength="200"
                    show-word-limit
                    :disabled="getMisDataConfig === '1'"
                    readonly
                />
              </el-form-item>
            </el-col>
          </template>

          <!-- 复位启机时显示的字段 -->
          <template v-else-if="finalizeForm.repairMethod === '2'">
            <el-col :span="12">
              <el-form-item label="复位方式" prop="resetMethod">
                <el-select
                  v-model="finalizeForm.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="附件（可选）">
              <preview :limit="8" v-model="finalizeForm.attachmentUrls" :filesize="5"></preview>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeFinalizeDialog">取 消</el-button>
          <el-button type="primary" @click="submitFinalize">确认结单</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 结束工单对话框 -->
    <el-dialog title="结束工单" v-model="completeDialogVisible" width="600px" append-to-body @close="closeCompleteDialog">
      <el-form ref="completeFormRef" :model="completeForm" :rules="completeRules" label-width="120px" label-position="top">
        <el-form-item label="处理结果描述" prop="completeDescription">
          <el-input
              v-model="completeForm.completeDescription"
              type="textarea"
              placeholder="请输入处理结果描述"
              maxlength="200"
              show-word-limit
              :rows="4"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeCompleteDialog">取 消</el-button>
          <el-button type="primary" @click="submitComplete">确认结束</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 评分对话框 -->
    <el-dialog title="工单评分" v-model="ratingDialogVisible" width="800px" append-to-body @close="closeRatingDialog">
      <el-form ref="ratingFormRef" :model="ratingForm" :rules="ratingRules" label-width="120px" label-position="top">
        <el-row>
          <el-col :span="12">
            <el-form-item label="工单编码"><el-input v-model="ratingForm.workOrderProjectNo" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="风机编号"><el-input v-model="ratingForm.pcsDeviceName" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工单状态">
              <el-select v-model="ratingForm.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="ratingForm.gxtCenter" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="场站"><el-input v-model="ratingForm.pcsStationName" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌"><el-input v-model="ratingForm.brand" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="故障代码"><el-input v-model="ratingForm.faultCode" disabled /> </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="故障信息">
              <el-input
                v-model="ratingForm.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="MIS工单编码">
              <el-input v-model="ratingForm.misOrderNo" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下发人"><el-input v-model="ratingForm.assignUserName" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下发时间"><el-input v-model="ratingForm.assignTime" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="接单人"><el-input v-model="ratingForm.acceptUserName" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="接单时间"><el-input v-model="ratingForm.acceptTime" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工作负责人"><el-input v-model="ratingForm.teamLeaderName" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开始时间"><el-input v-model="ratingForm.realStartTime" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间"><el-input v-model="ratingForm.realEndTime" disabled /> </el-form-item>
          </el-col>
<!--          <el-col :span="12">
            <el-form-item label="故障描述">{{ ratingForm.faultDesc || '无' }}</el-form-item>
          </el-col>-->
<!--          <el-col :span="24">-->
<!--            <el-form-item label="维修总结">-->
<!--              <el-input-->
<!--                  v-model="ratingForm.content"-->
<!--                  type="textarea"-->
<!--                  :rows="3"-->
<!--                  disabled-->
<!--              />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="检修类型">-->
<!--              <el-select v-model="ratingForm.maintenanceType" style="width: 100%" disabled>-->
<!--                <el-option-->
<!--                    v-for="dict in gxt_maintenance_type"-->
<!--                    :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="ratingForm.workGroupMemberName" disabled /></el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="附件">
              <preview :limit="8" v-model="ratingForm.attachmentUrls" :filesize="5" disabled></preview>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="评分" prop="score">
              <el-input-number
                  v-model="ratingForm.score"
                  :min="1"
                  :max="10"
                  controls-position="right"
                  style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="点评">
              <el-input
                  v-model="ratingForm.reviewContent"
                  type="textarea"
                  placeholder="请输入点评"
                  maxlength="200"
                  show-word-limit
                  :rows="3"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeRatingDialog">取 消</el-button>
          <el-button type="primary" @click="submitRating">提交评分</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 开始处理对话框 -->
    <el-dialog title="开始工单" v-model="startDialogVisible" width="500px" append-to-body @close="closeStartDialog">
      <el-form label-width="120px" label-position="top">
        <el-row>
          <el-col :span="12">
            <el-form-item label="工单编码">
              {{ startForm.workOrderProjectNo }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="风机编号">
              {{ startForm.pcsDeviceName }}
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeStartDialog">取 消</el-button>
          <el-button type="primary" @click="submitStart">确认开始</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 复运对话框 -->
    <el-dialog title="复运" v-model="restartDialogVisible" width="800px" append-to-body @close="closeRestartDialog">
      <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="restartFormRef" :model="restartForm" :rules="restartRules" label-width="120px" label-position="top">
        <el-row>
          <el-col :span="12">
            <el-form-item label="工单编码"><el-input v-model="restartForm.workOrderProjectNo" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="风机编号"><el-input v-model="restartForm.pcsDeviceName" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="维保中心"><el-input v-model="restartForm.gxtCenter" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="场站"><el-input v-model="restartForm.pcsStationName" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌"><el-input v-model="restartForm.brand" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发生时间"><el-input v-model="restartForm.occurTime" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="MIS工单编码"><el-input v-model="restartForm.misOrderNo" disabled /> </el-form-item>
          </el-col>
<!--          <el-col :span="12">-->
<!--            <el-form-item label="检修类型">-->
<!--              <el-select v-model="restartForm.maintenanceType" style="width: 100%" disabled>-->
<!--                <el-option-->
<!--                    v-for="dict in gxt_maintenance_type"-->
<!--                    :key="dict.value"-->
<!--                    :label="dict.label"-->
<!--                    :value="dict.value"-->
<!--                />-->
<!--              </el-select>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="24">-->
<!--            <el-form-item label="维修总结">-->
<!--              <el-input-->
<!--                v-model="restartForm.content"-->
<!--                type="textarea"-->
<!--                :rows="3"-->
<!--                disabled-->
<!--              />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="24">-->
<!--            <el-form-item label="附件">-->
<!--              <preview :limit="8" v-model="restartForm.attachmentUrls" :filesize="5" disabled></preview>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
          <el-col :span="12">
            <el-form-item label="恢复运行时间" prop="restartTime">
              <el-date-picker
                  v-model="restartForm.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-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeRestartDialog">取 消</el-button>
          <el-button type="primary" @click="submitRestart">确认复运</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 作废对话框 -->
    <el-dialog title="作废工单" v-model="invalidateDialogVisible" width="800px" append-to-body @close="closeInvalidateDialog">
      <el-alert type="warning" :closable="false" style="border-color: #f59e0b; background-color: #fffbeb; color: #92400e; height: 35px;">
        <template #default>
          <i class="fa fa-exclamation-triangle mr-2" style="color: #92400e;"> 作废后工单将不可恢复，请谨慎操作。</i>
        </template>
      </el-alert>
      <el-form ref="invalidateFormRef" :model="invalidateForm" :rules="invalidateRules" label-width="120px" label-position="top">
        <el-row>
          <el-col :span="12">
            <el-form-item label="工单编码"><el-input v-model="invalidateForm.workOrderProjectNo" disabled /></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="风机编号"><el-input v-model="invalidateForm.pcsDeviceName" disabled /></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工单状态">
              <el-select v-model="invalidateForm.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="invalidateForm.gxtCenter" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="场站"><el-input v-model="invalidateForm.pcsStationName" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌"><el-input v-model="invalidateForm.brand" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="故障代码"><el-input v-model="invalidateForm.faultCode" disabled /></el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="故障信息">
              <el-input
                v-model="invalidateForm.faultBarcode"
                type="textarea"
                placeholder="请输入故障信息"
                maxlength="100"
                show-word-limit
                :rows="3"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="作废原因" prop="invalidReason">
              <el-input
                  v-model="invalidateForm.invalidReason"
                  type="textarea"
                  placeholder="请输入作废原因"
                  maxlength="200"
                  show-word-limit
                  :rows="4"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeInvalidateDialog">取 消</el-button>
          <el-button type="primary" @click="submitInvalidate">确认作废</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 审批对话框 -->
    <el-dialog title="退回" v-model="returnDialogVisible" width="800px" append-to-body @close="closeReturnDialog">
      <el-alert type="info" :closable="false" style="border-color: #a855f7; background-color: #f8f5ff; color: #6d28d9; height: 35px;">
        <template #default>
          <i class="fa fa-sign-in mr-2" style="color: #6d28d9;"> 请选择退回类型填写退回原因完成工单退回。</i>
        </template>
      </el-alert>
      <!-- 工单信息 -->
      <h3 class="text-sm font-medium text-gray-800 mb-3"></h3>
      <el-form ref="returnFormRef" :model="returnForm" :rules="returnRules" label-width="120px" label-position="top">
        <el-row>
          <el-col :span="12">
            <el-form-item label="工单编码"><el-input v-model="returnForm.workOrderProjectNo" disabled /></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="风机编号"><el-input v-model="returnForm.pcsDeviceName" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工单状态">
              <el-select v-model="returnForm.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="returnForm.gxtCenter" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="场站"><el-input v-model="returnForm.pcsStationName" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌"><el-input v-model="returnForm.brand" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工作负责人"><el-input v-model="returnForm.teamLeaderName" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="退回类型" prop="returnType">
              <el-select v-model="returnForm.returnType" style="width: 100%">
                <el-option
                    v-for="dict in gxt_return_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!--        <el-form-item label="审批决定" prop="approvalStatus">
                  <el-radio-group v-model="returnForm.approvalStatus" @change="toggleRejectionReason">
                    <el-radio label="approved">通过</el-radio>
                    <el-radio label="rejected">驳回</el-radio>
                  </el-radio-group>
                </el-form-item>-->
        <el-form-item label="退回原因" prop="returnReason">
          <el-input
              v-model="returnForm.returnReason"
              type="textarea"
              placeholder="请输入审批意见"
              maxlength="100"
              show-word-limit
              :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeReturnDialog">取 消</el-button>
          <el-button type="primary" @click="submitReturn()">退 回</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看工单详情对话框 -->
    <el-dialog title="查看工单详情" v-model="viewDialogVisible" width="1000px" append-to-body>
      <el-row :gutter="20">
        <!-- 工单信息 -->
        <el-col :span="8">
          <div class="info-section">
            <h3 class="section-title">工单信息</h3>
            <div class="info-content">
              <el-form label-width="100px" label-position="top">
                <el-row :gutter="20">
                  <el-col :span="24">
                    <el-form-item label="工单编码">{{ viewForm.workOrderProjectNo }}</el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="工单状态">
                      <dict-tag :options="gxt_work_order_status" :value="viewForm.workOrderStatus" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="风机编号">{{ viewForm.pcsDeviceName || '-' }}</el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="维保中心">{{ viewForm.gxtCenter || '-' }}</el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="场站">{{ viewForm.pcsStationName || '-' }}</el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="品牌">{{ viewForm.brand || '-' }}</el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="机型">{{ viewForm.model || '-' }}</el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="发生时间">{{ parseTime(viewForm.occurTime, '{y}-{m}-{d} {h}:{i}') || '-' }}</el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="故障代码">{{ viewForm.faultCode || '-' }}</el-form-item>
                  </el-col>
<!--                  <el-col :span="24">
                    <el-form-item label="故障描述">{{ viewForm.faultDesc }}</el-form-item>
                  </el-col>-->
                </el-row>
              </el-form>
            </div>
          </div>
        </el-col>

        <!-- 处理信息 -->
        <el-col :span="8">
          <div class="info-section">
            <h3 class="section-title">处理信息</h3>
            <div class="info-content">
              <el-form label-width="100px" label-position="top">
                <el-row :gutter="20">
                  <el-col :span="24">
                    <el-form-item label="下发人">{{ viewForm.assignUserName || '-' }}</el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="下发时间">{{ parseTime(viewForm.assignTime, '{y}-{m}-{d} {h}:{i}') || '-' }}</el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="接单人">{{ viewForm.acceptUserName || '-'}}</el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="接单时间">{{ parseTime(viewForm.acceptTime, '{y}-{m}-{d} {h}:{i}') || '-' }}</el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="工作负责人">{{ viewForm.teamLeaderName || '-' }}</el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="检修人员">{{ viewForm.workGroupMemberName || '-' }}</el-form-item>
                  </el-col>
<!--                  <el-col :span="24">-->
<!--                    <el-form-item label="检修类型">-->
<!--                      <dict-tag :options="gxt_maintenance_type" :value="viewForm.maintenanceType" />-->
<!--                    </el-form-item>-->
<!--                  </el-col>-->
<!--                  <el-col :span="24">-->
<!--                    <el-form-item label="维修总结">{{ viewForm.content }}</el-form-item>-->
<!--                  </el-col>-->
                  <el-col :span="24">
                    <el-form-item label="维修方式">
                      <dict-tag :options="gxt_repair_method" :value="viewForm.repairMethod" />
                    </el-form-item>
                  </el-col>
                  <template v-if="viewForm.repairMethod !== '2'">
                    <el-col :span="24">
                      <el-form-item label="MIS工单编码">{{ viewForm.misOrderNo || '-' }}</el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="开始时间">{{ parseTime(viewForm.realStartTime, '{y}-{m}-{d} {h}:{i}') || '-' }}</el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="结束时间">{{ parseTime(viewForm.realEndTime, '{y}-{m}-{d} {h}:{i}') || '-' }}</el-form-item>
                    </el-col>
                  </template>
                  <template v-if="viewForm.repairMethod === '2'">
                    <el-col :span="24">
                      <el-form-item label="复位方式">
                        <dict-tag :options="gxt_reset_method" :value="viewForm.resetMethod" />
                      </el-form-item>
                    </el-col> 
                  </template>
                  <el-col :span="24">
                    <el-form-item label="恢复运行时间">{{ parseTime(viewForm.restartTime, '{y}-{m}-{d} {h}:{i}') || '-' }}</el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
          </div>
        </el-col>

        <!-- 工单流转记录 -->
        <el-col :span="8">
          <div class="info-section">
            <h3 class="section-title">工单流转</h3>
            <div class="flow-history">
              <el-timeline>
                <el-timeline-item type="primary"
                                  v-for="(flow, index) in flowList"
                                  :key="index"
                                  :timestamp="parseTime(flow.actionTime, '{y}-{m}-{d} {h}:{i}')"
                >
                  <div class="flow-item">
                    <h4><dict-tag :options="gxt_repair_order_flow_action_type" :value="flow.actionType" /></h4>
                    <p>
                      <!--                      {{ flow.actionRemark }}<br>-->
                      {{ flow.operatorName }}
                    </p>
                  </div>
                </el-timeline-item>
              </el-timeline>
            </div>
          </div>
        </el-col>
      </el-row>
      <el-form label-position="top">
        <el-row>
          <el-col :span="24">
            <el-form-item label="故障信息">
              <div class="content-text">{{ viewForm.faultBarcode || '-' }}</div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 附件信息 -->
      <div class="info-section" v-if="viewForm.attachmentUrls">
        <h3 class="section-title">结单附件</h3>
        <el-row>
          <el-col :span="24">
            <el-form-item label="附件">
              <preview :limit="8" v-model="viewForm.attachmentUrls" :filesize="5" disabled></preview>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeViewDialog">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- MIS工单导入对话框 -->
    <el-dialog :title="uploadMis.title" v-model="uploadMis.open" width="400px" append-to-body>
      <el-upload ref="uploadMisRef" :limit="1" accept=".xlsx, .xls" :headers="uploadMis.headers" :action="uploadMis.url + '?updateSupport=' + uploadMis.updateSupport" :disabled="uploadMis.isUploading" :on-progress="handleFileUploadProgressMis" :on-success="handleFileSuccessMis" :on-change="handleFileChangeMis" :on-remove="handleFileRemoveMis" :auto-upload="false" drag>
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
<!--            <div class="el-upload__tip">
              <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的工单数据
            </div>-->
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplateMis">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileFormMis">确 定</el-button>
          <el-button @click="uploadMis.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 维修工单导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :on-change="handleFileChange" :on-remove="handleFileRemove" :auto-upload="false" drag>
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的工单数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

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

<script setup name="RepairOrder">
import { getToken } from "@/utils/auth"
import {
  listRepairOrder,
  getRepairOrder,
  delRepairOrder,
  addRepairOrder,
  updateRepairOrder,
  assignRepairOrder,
  acceptRepairOrder,
  startRepairOrder,
  pauseRepairOrder,
  processDoneRepairOrder,
  ratingRepairOrder,
  suspendRepairOrder,
  resumeRepairOrder,
  approveSuspendRepairOrder,
  finalizeRepairOrder,
  restartRepairOrder,
  getRepairOrderByMisOrderNo,
  revokeRepairOrder,
  invalidateRepairOrder,
  returnRepairOrder
} from "@/api/gxt/repairOrder";
import { listDept,getDept } from "@/api/system/dept";
import { listFaultCodes } from "@/api/gxt/faultCodes"
/*import { listGxtOrder } from "@/api/gxt/gxtOrder";*/
import { listUser,listUserNoPermi } from "@/api/system/user";
import EquipmentSelectSingle from "@/components/equipmentSelect/single.vue"
import { ElMessage, ElMessageBox, ElNotification, ElLoading } from 'element-plus'
import { listMaintenanceCenters, listStationsByMaintenanceCenter } from "@/api/gxt/equipment"
import preview from '@/components/FileUpload/preview.vue'
import { getConfigKey } from "@/api/system/config"
import {genCode} from "@/api/system/autocode/rule.js";
import MisInfoSelectSingle from "@/components/misInfoSelect/single.vue";
import {listMisInfo, listWorkPerson} from "@/api/gxt/misInfo.js";
import {listGxtOrder} from "@/api/gxt/gxtOrder.js";
import useUserStore from '@/store/modules/user'


const { proxy } = getCurrentInstance()
const { gxt_maintenance_type, gxt_work_order_status, gxt_order_priority_type,gxt_repair_order_flow_action_type,gxt_order_suspend_reason,gxt_repair_method,gxt_reset_method,gxt_return_type } = proxy.useDict("gxt_maintenance_type", "gxt_work_order_status", "gxt_order_priority_type","gxt_repair_order_flow_action_type","gxt_order_suspend_reason","gxt_repair_method","gxt_reset_method","gxt_return_type")

// 数据列表相关
const repairOrderList = ref([])

const openDialog = ref(false)
const viewDialogVisible = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const dialogTitle = ref("")
const tableHeight = ref(window.innerHeight - 300)
const startDialogVisible = ref(false)  // 添加开始处理对话框控制变量
const misInfoSelectVisible = ref(false)
let commonKey = 0
const optType = ref("")

// 表单相关
const repairOrderRef = ref(null)
const queryRef = ref(null)
const assignFormRef = ref(null)
const acceptFormRef = ref(null)
const suspendFormRef = ref(null)
const completeFormRef = ref(null)
const ratingFormRef = ref(null)
const startFormRef = ref(null)  // 添加开始处理表单引用
const restartFormRef = ref(null)  // 添加复运表单引用
const invalidateFormRef = ref(null)  // 添加作废表单引用
const returnFormRef = ref(null)

// 各种表单数据
const form = ref({})
const viewForm = ref({})
const assignForm = ref({})
const acceptForm = ref({
  id: null,
  workOrderProjectNo: null,
  pcsDeviceName: null,
  maintenanceType: null,
  workOrderStatus: null,
  gxtCenter: null,
  pcsStationName: null,
  brand: null,
  faultCode: null,
  faultDesc: null,
  relatedOrderCode: null,
  relatedOrderContent: null,
  teamLeaderName: null,
  selectedMembers: [],
  repairOrderPersonList: [],
  pcsStationId: null // 添加场站ID用于查询用户
})
const suspendForm = ref({})
const approveForm = ref({})
const completeForm = ref({})
const finalizeForm = ref({
  repairOrderPersonList: [],
})
const invalidateForm = ref({}) // 添加作废表单
const ratingForm = ref({
  score: null
})
const startForm = ref({})  // 添加开始处理表单数据
const restartForm = ref({
  realEndTime: null
  // restartTime: '' // 必须有这个字段
})  // 添加复运表单数据
const returnForm = ref({})

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

// 下发对话框中的维保工单搜索相关
const workOrderSearchLoading = ref(false)
const workOrderOptions = ref([])

// 文件列表
const fileList = ref([])

// 对话框显示控制
const assignDialogVisible = ref(false);
const acceptDialogVisible = ref(false);
const userList = ref([]); // 添加用户列表
const suspendDialogVisible = ref(false)
const approveDialogVisible = ref(false)
const completeDialogVisible = ref(false)
const finalizeDialogVisible = ref(false)
const invalidateDialogVisible = ref(false) // 添加作废对话框显示控制
const ratingDialogVisible = ref(false)
const equipmentSelectVisible = ref(false)
const restartDialogVisible = ref(false)  // 添加复运对话框显示控制
const returnDialogVisible = ref(false)

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

// 维保中心和场站选项
const maintenanceCenterOptions = ref([])
const stationOptions = ref([])

// 故障代码选项
const faultCodeOptions = 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

const userStore = useUserStore();


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 {};
};

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

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

// 工作负责人快速检索方法
/** 工作负责人输入框获取焦点 */
const handleTeamLeaderInputFocus = () => {
  showTeamLeaderQuickSelect.value = true
  // 如果已有输入内容，立即搜索
  if (acceptForm.value.teamLeaderName && acceptForm.value.teamLeaderName.trim()) {
    handleTeamLeaderInput(acceptForm.value.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)
  }
  filterQuickUserList(searchText)
  // 设置新的定时器，防抖处理（300ms）
  // teamLeaderSearchTimer.value = setTimeout(() => {
  //   searchTeamLeaderList(searchText)
  // }, 300)
}

/** 搜索工作负责人列表 */
const searchTeamLeaderList = async (keyword) => {
  if (!keyword) {
    quickTeamLeaderList.value = []
    return
  }

  teamLeaderLoading.value = true
  try {
    const response = await listUserNoPermi({
      nickName: keyword,
      // 可以根据需要添加其他搜索条件
      status: '0' // 只搜索启用状态的用户
    })

    quickTeamLeaderList.value = response.data || []

  } catch (error) {
    console.error('搜索工作负责人失败:', error)
    proxy.$modal.msgError('搜索失败，请重试')
    quickTeamLeaderList.value = []
  } finally {
    teamLeaderLoading.value = false
  }
}

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

  // 记录当前维保中心ID
  lastLoadedCenterId.value = acceptForm.value.gxtCenterId;

  teamLeaderLoading.value = true
  try {
    // 加载当前部门下的用户列表
    const response = await listUserNoPermi({
      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) => {
  acceptForm.value.teamLeaderId = item.userId
  acceptForm.value.teamLeaderName = item.nickName
  showTeamLeaderQuickSelect.value = false
}

/** 清空工作负责人 */
const handleTeamLeaderClear = () => {
  acceptForm.value.teamLeaderId = undefined
  acceptForm.value.teamLeaderName = ''
  quickTeamLeaderList.value = []
  showTeamLeaderQuickSelect.value = false
}

// MIS工单快速检索相关响应式数据
const showMisNoQuickSelect = ref(false)
const quickMisNoList = ref([])
const misNoLoading = ref(false)
const misNoSearchTimer = ref(null)

// 快速检索方法
/** MIS工单编码输入框获取焦点 */
const handleMisNoInputFocus = () => {
  showMisNoQuickSelect.value = true
  // 如果已有输入内容，立即搜索
  if (form.misNo && form.misNo.trim()) {
    handleMisNoInput(form.misNo)
  }
}

/** 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)
  }

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

/** 搜索MIS工单列表 */
const searchMisNoList = async (keyword) => {
  if (!keyword) {
    quickMisNoList.value = []
    return
  }

  misNoLoading.value = true
  try {
    const response = await listMisInfo({
      pageNum: 1,
      // pageSize: 10, // 只显示前10条结果
      misNo: keyword,
      pcsDeviceName: keyword,
      pcsStationName: keyword
      // 注意：这里假设后端API支持这些字段的模糊查询
      // 如果后端不支持多字段同时查询，可能需要调整
    })

    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)
    proxy.$modal.msgError('搜索失败，请重试')
    quickMisNoList.value = []
  } finally {
    misNoLoading.value = false
  }
}

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

/** 清空MIS工单编码 */
const handleMisNoClear = () => {
  // 清空与MIS工单相关的字段
  finalizeForm.value.misOrderNo = null
  finalizeForm.value.realStartTime = null
  finalizeForm.value.realEndTime = null
  finalizeForm.value.repairOrderPersonList = [];
  finalizeForm.value.workGroupMemberName = null
  quickMisNoList.value = []
  showMisNoQuickSelect.value = false
}

/** 查询故障代码列表 */
function getFaultCodeList() {
  listFaultCodes({ isActive: 0 }).then(response => {
    faultCodeOptions.value = response.rows;
  });
}

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  workOrderProjectNo: null,
  workOrderStatus: null,
  gxtCenterId: null,
  gxtCenter: null,
  pcsStationId: null,
  pcsStationName: null,
  pcsDeviceId: null,
  pcsDeviceName: null,
  brand: null,
  model: null,
  faultCode: null,
  faultBarcode: null,
  assignTime: null,
  assignUserId: null,
  assignUserName: null,
  acceptTime: null,
  acceptUserId: null,
  acceptUserName: null,
  realStartTime: null,
  realEndTime: null,
  teamLeaderId: null,
  teamLeaderName: null,
  workGroupMemberId: null,
  workGroupMemberName: null,
  content: null,
  planHour: null,
  priorityType: null,
  score: null,
  reviewContent: null,
  maintenanceType: null
})

// 表单验证规则
const rules = ref({
  workOrderProjectNo: [
    { required: true, message: "工单编码不能为空", trigger: "blur" }
  ],
  pcsDeviceName: [
    { required: true, message: "风机编号不能为空", trigger: "blur" }
  ],
  /*faultCode: [
    { required: true, message: "请选择故障代码", trigger: "change" }
  ],*/
  occurTime: [
    { required: true, message: "请选择发生时间", trigger: "change" },
    {
      validator: (rule, value, callback) => {
        if (value && new Date(value) > new Date()) {
          callback(new Error('发生时间不能大于当前时间'));
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ],
  // maintenanceType: [
  //   { required: true, message: "请选择检修类型", trigger: "change" }
  // ],
  /* priorityType: [
     { required: true, message: "请选择优先级", trigger: "change" }
   ],*/
  faultBarcode: [
    { required: true, message: "故障信息不能为空", trigger: "blur" }
  ],
})

// 接单表单验证规则
const acceptRules = ref({
  teamLeaderId: [
    { required: true, message: "请选择工作负责人", trigger: "change" }
  ],
  /*selectedMembers: [
    { required: true, message: "请至少选择一名检修人员", trigger: "change" }
  ]*/
})

// 挂起表单验证规则
const suspendRules = ref({
  suspendReason: [
    { required: true, message: "请选择挂起原因", trigger: "change" }
  ],
  /*suspendDescription: [
    { required: true, message: "请输入详细说明", trigger: "blur" }
  ]*/
})

// 审批表单验证规则
const approveRules = ref({
  /*approvalStatus: [
    { required: true, message: "请选择审批决定", trigger: "change" }
  ],
  rejectionReason: [
    { required: true, message: "请输入驳回原因", trigger: "blur" }
  ]*/
})

// 结单表单验证规则
const finalizeRules = ref({
  // maintenanceType: [
  //   { required: true, message: "请选择检修类型", trigger: "change" }
  // ],
  /*selectedMembers: [
    { required: true, message: "请至少选择一名检修人员", trigger: "change" }
  ],*/
  // content: [
  //   { required: true, message: "请输入维修总结", trigger: "blur" }
  // ],
  repairMethod: [
    { required: true, message: "请选择维修方式", trigger: "change" }
  ],
  misOrderNo: [
    { required: true, message: "MIS工单编码不能为空", trigger: "blur" }
  ],
  resetMethod: [
    { required: true, message: "请选择复位方式", trigger: "change" }
  ]
})

// 作废表单验证规则
const invalidateRules = ref({
  invalidReason: [
    { required: true, message: "请输入作废原因", trigger: "blur" }
  ]
})

// 评分表单验证规则
const ratingRules = ref({
  score: [
    { required: true, message: "请评分", trigger: "change" },
    { type: "number", min: 1, max: 10, message: "评分必须在1-10之间", trigger: "change" }
  ]
})

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

// 退回表单验证规则
const returnRules = ref({
  returnType: [
    { required: true, message: "请选择退回类型", trigger: "change" }
  ],
  returnReason: [
    { required: true, message: "请输入退回原因", trigger: "blur" }
  ]
})

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

// 关闭接单对话框并重置表单
function closeAcceptDialog() {
  acceptDialogVisible.value = false
  acceptForm.value = {}
  proxy.resetForm("acceptFormRef")
}

// 关闭下发表单对话框并重置表单
function closeAssignDialog() {
  assignDialogVisible.value = false
  assignForm.value = {}
  proxy.resetForm("assignFormRef")
}

// 关闭挂起对话框并重置表单
function closeSuspendDialog() {
  suspendDialogVisible.value = false
  suspendForm.value = {}
  proxy.resetForm("suspendFormRef")
}

// 关闭审批对话框并重置表单
function closeApproveDialog() {
  approveDialogVisible.value = false
  approveForm.value = {}
  proxy.resetForm("approveFormRef")
}

// 关闭结单对话框并重置表单
function closeFinalizeDialog() {
  finalizeDialogVisible.value = false
  finalizeForm.value = {}
  proxy.resetForm("finalizeFormRef")
}

// 关闭结束工单对话框并重置表单
function closeCompleteDialog() {
  completeDialogVisible.value = false
  completeForm.value = {}
  proxy.resetForm("completeFormRef")
}

// 关闭评分对话框并重置表单
function closeRatingDialog() {
  ratingDialogVisible.value = false
  ratingForm.value = {}
  proxy.resetForm("ratingFormRef")
}

// 关闭开始处理对话框并重置表单
function closeStartDialog() {
  startDialogVisible.value = false
  startForm.value = {}
  proxy.resetForm("startFormRef")
}

// 关闭复运对话框并重置表单
function closeRestartDialog() {
  restartDialogVisible.value = false
  restartForm.value = {}
  proxy.resetForm("restartFormRef")
}

// 关闭作废对话框并重置表单
function closeInvalidateDialog() {
  invalidateDialogVisible.value = false
  invalidateForm.value = {}
  proxy.resetForm("invalidateFormRef")
}

// 关闭查看详情对话框并重置表单
function closeViewDialog() {
  viewDialogVisible.value = false
  viewForm.value = {}
  flowList.value = []
}

// 关闭审批对话框并重置表单
function closeReturnDialog() {
  returnDialogVisible.value = false
  returnForm.value = {}
  proxy.resetForm("returnFormRef")
}

onMounted(() => {
  getList()
  getMaintenanceCenterAndStationList()
  getFaultCodeList()
  getGetMisDataConfig() // 获取配置参数
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})

/** 获取配置参数 gxt.repairOder.getMisData */
function getGetMisDataConfig() {
  getConfigKey("gxt.repairOder.getMisData").then(response => {
    getMisDataConfig.value = response.msg || "0";
  }).catch(error => {
    console.error("获取配置参数失败:", error);
    getMisDataConfig.value = "0"; // 获取失败时默认为可手动输入
  });
}

/** 查询维修工单列表 */
function getList() {
  loading.value = true
  listRepairOrder(queryParams.value).then(response => {
    repairOrderList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/** 查询维保中心和场站列表 */
/*function getMaintenanceCenterAndStationList() {
  listDept({}).then(response => {
    const depts = response.data;

    // 筛选出维保中心(level=2)
    maintenanceCenterOptions.value = depts.filter(dept => dept.level === "2");

    // 筛选出场站(level=3)
    const stations = depts.filter(dept => dept.level === "3");

    // 如果已选择维保中心，则筛选出该维保中心下的场站
    if (queryParams.value.gxtCenter) {
      const selectedMaintenanceCenter = maintenanceCenterOptions.value.find(
          center => center.deptName === queryParams.value.gxtCenter
      );

      if (selectedMaintenanceCenter) {
        stationOptions.value = stations.filter(
            station => station.ancestors.includes(selectedMaintenanceCenter.deptId)
        );
      } else {
        stationOptions.value = [];
      }
    } else {
      // 如果未选择维保中心，则清空场站选项
      stationOptions.value = [];
    }
  });
}*/
function getMaintenanceCenterAndStationList() {
  listMaintenanceCenters().then(response => {
    maintenanceCenterOptions.value = response.data.map(item => {
      return { deptName: item, deptId: item };
    });

    // 如果已选择维保中心，则筛选出该维保中心下的场站
    if (queryParams.value.maintenanceCenter) {
      listStationsByMaintenanceCenter(queryParams.value.maintenanceCenter).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) {
    listDept({}).then(response => {
      const depts = response.data;
      const stations = depts.filter(dept => dept.level === "3");

      // 找到选中的维保中心
      const selectedMaintenanceCenter = maintenanceCenterOptions.value.find(
          center => center.deptName === selectedCenter
      );

      if (selectedMaintenanceCenter) {
        // 筛选出该维保中心下的场站
        stationOptions.value = stations.filter(
            station => station.ancestors.includes(selectedMaintenanceCenter.deptId)
        );
      }
    });
  } else {
    // 如果未选择维保中心，则清空场站选项
    stationOptions.value = [];
  }
}*/
function handleMaintenanceCenterChange(selectedCenter) {
  // 清空场站选择
  queryParams.value.station = null;

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

/**
 * 根据部门ID获取部门信息，并根据level判断是否需要查找父部门
 * @param {Number} deptId 部门ID
 * @returns {Promise<Number>} 返回level为3的部门ID
 */
function getDeptAndUserByLevel(deptId) {
  return new Promise((resolve) => {
    // 获取部门信息
    getDeptInfoAndParent(deptId).then(dept => {
      resolve(dept.deptId);
    });
  });
}
/**
 * 递归获取部门信息，查找父部门直到level为3
 * @param {Number} deptId 部门ID
 * @returns {Promise<Object>} 返回level为3的部门对象
 */
function getDeptInfoAndParent(deptId) {
  return new Promise((resolve) => {
    getDept(deptId).then(response => {
      const dept = response.data;
      // 如果部门level为3，直接返回
      if (dept.level === "3") {
        resolve(dept);
      }
      // 如果有祖先部门，则继续向上查找
      else if (dept.ancestors) {
        // 从ancestors中提取父部门ID
        // ancestors格式类似 "0,100,101,102"
        const ancestorIds = dept.ancestors.split(',');
        if (ancestorIds.length <= 1){
          resolve(dept);
        }else {
          const parentDeptId = ancestorIds[ancestorIds.length - 1];
          // 递归获取父部门信息
          getDeptInfoAndParent(parentDeptId).then(parentDept => {
            resolve(parentDept);
          });
        }
      }
      // 其他情况也直接返回
      else {
        resolve(dept);
      }
    }).catch(error => {
      // 如果获取部门信息失败，返回null
      console.error("获取部门信息失败:", error);
      resolve(null);
    });
  });
}

// 取消按钮
function cancel() {
  openDialog.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {}
  proxy.resetForm("repairOrderRef")
}

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

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

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

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

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  //生成工单编码
  genCode('REPAIR_ORDER_CODE').then(response =>{
    form.value.workOrderProjectNo = response;
  });
  openDialog.value = true
  dialogTitle.value = "新建维修工单"
  optType.value = "add"
  // 设置默认发生时间
  form.value.occurTime = now
}

/** 修改按钮操作 */
function handleEdit(row) {
  reset()
  const id = row.id || ids.value
  getRepairOrder(id).then(response => {
    form.value = response.data
    openDialog.value = true
    dialogTitle.value = "下发"
    optType.value = "edit"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["repairOrderRef"].validate(valid => {
    if (valid) {
      form.value.workOrderStatus = "to_issue"
      if (form.value.id != null) {
        updateRepairOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          openDialog.value = false
          getList()
        })
      } else {
        addRepairOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          openDialog.value = false
          getList()
        })
      }
    }
  })
}

/** 保存并下发 */
function submitFormAndIssue() {
  proxy.$refs["repairOrderRef"].validate(valid => {
    if (valid) {
      // 设置状态为待接单
      form.value.workOrderStatus = "assigned"
      if (form.value.id != null) {
        updateRepairOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          openDialog.value = false
          getList()
        })
      } else {
        addRepairOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          openDialog.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const ids = row.id || ids.value
  const workOrderProjectNo = row.workOrderProjectNo || (repairOrderList.value.find(item => item.id === ids)?.workOrderProjectNo)
  proxy.$modal.confirm('是否确认删除维修工单编码为"' + workOrderProjectNo + '"的数据项？').then(function() {
    return delRepairOrder(ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('gxt/repairOrder/export', {
    ...queryParams.value
  }, `repairOrder_${new Date().getTime()}.xlsx`)
}



/** 故障代码变化处理 */
function handleFaultCodeChange(value) {
  if (value === '无') {
    // 当选择"无"时，故障信息设置为"-"并允许手动输入
    form.value.faultBarcode = "-";
  } else {
    // 当选择具体的故障代码时，自动填充故障信息并设为只读
    const selectedFaultCode = faultCodeOptions.value.find(item => item.faultCode === value);
    if (selectedFaultCode) {
      form.value.faultBarcode = selectedFaultCode.faultBarcode || "";
    } else {
      form.value.faultBarcode = "";
    }
  }
}


/** 获取字典标签文本 */
function getDictLabel(dictOptions, value) {
  const dict = dictOptions.find(item => item.value === value);
  return dict ? dict.label : value;
}


/** 下发操作 */
function handleAssign(row) {
  getRepairOrder(row.id).then(response => {
    assignForm.value = response.data
    // 初始化维保工单选项为空
    workOrderOptions.value = []
    assignDialogVisible.value = true
  })
}

/** 关联维保工单变化处理 */
function handleRelatedOrderChange() {
  // 当关联维保工单编码输入时，如果清空了内容，则清空维保内容
  if (!assignForm.value.relatedOrderCode) {
    assignForm.value.relatedOrderContent = ""
  }
}

/** 搜索维保工单 */
/*function searchWorkOrders(query) {
  if (!query) {
    workOrderOptions.value = []
    return
  }

  workOrderSearchLoading.value = true
  listGxtOrder({ workOrderProjectNo: query }).then(response => {
    workOrderOptions.value = response.rows
    workOrderSearchLoading.value = false
  }).catch(() => {
    workOrderSearchLoading.value = false
    workOrderOptions.value = []
  })
}*/

/** 选择维保工单 */
function handleWorkOrderChange(val) {
  if (!val) {
    assignForm.value.relatedOrderContent = ""
    return
  }

  // 查找选中的维保工单
  const selectedWorkOrder = workOrderOptions.value.find(item => item.workOrderProjectNo === val)
  if (selectedWorkOrder) {
    // 自动填充维保内容
    assignForm.value.relatedOrderContent = selectedWorkOrder.content || ""
  } else {
    assignForm.value.relatedOrderContent = ""
  }
}

/** 提交下发 */
async function submitAssign() {
  proxy.$refs["assignFormRef"].validate(async valid => {
    if (valid) {
      try {
        await assignRepairOrder(assignForm.value)

        proxy.$modal.msgSuccess("下发成功")
        assignDialogVisible.value = false
        getList()
      } catch (error) {
        proxy.$modal.msgError("下发失败: " + error.message)
      }
    }
  })
}

/** 接单操作 */
function handleAccept(row) {
  getRepairOrder(row.id).then(response => {
    acceptForm.value = { ...response.data, selectedMembers: [] }
    // 获取场站ID用于查询用户
    acceptForm.value.pcsStationId = response.data.pcsStationId
    acceptForm.value.pcsStationPid = response.data.pcsStationPid
    if (lastLoadedCenterId.value !== acceptForm.value.gxtCenterId) {
      allUserList.value = [];
    }

    // 预加载工作负责人列表
    loadQuickTeamLeaderList()
    acceptDialogVisible.value = true
  })
}

/** 提交接单 */
async function submitAccept() {
  proxy.$refs["acceptFormRef"].validate(async valid => {
    if (valid) {
      try {
        // 更新检修人员列表
        //handleMembersChange('acceptForm');
        await acceptRepairOrder(acceptForm.value)

        proxy.$modal.msgSuccess("接单成功")
        acceptDialogVisible.value = false
        getList()
      } catch (error) {
        proxy.$modal.msgError("接单失败: " + error.message)
      }
    }
  })
}

/** 开始操作 */
function handleStart(row) {
  /*startForm.value = {
    id: row.id,
    workOrderProjectNo: row.workOrderProjectNo,
    pcsDeviceName: row.pcsDeviceName
  }
  startDialogVisible.value = true*/
  ElMessageBox.confirm('确定要恢复工单"' + row.workOrderProjectNo + '"吗？', '提示', {
    confirmButtonText: '确认恢复',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(function() {
    startRepairOrder(row);
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("恢复成功")
  }).catch(() => {})
}

/** 提交开始处理 */
async function submitStart() {
  try {
    await startRepairOrder(startForm.value);

    proxy.$modal.msgSuccess("工单已开始处理");
    startDialogVisible.value = false;
    getList();
  } catch (error) {
    proxy.$modal.msgError("操作失败: " + error.message);
  }
}

/** 暂停操作 */
async function handlePause(row) {
  proxy.$modal.confirm('是否确认暂停该工单？').then(async function() {
    try {
      const updateData = {
        id: row.id,
        workOrderStatus: "paused"
      }

      await pauseRepairOrder(updateData)

      proxy.$modal.msgSuccess("工单已暂停")
      getList()
    } catch (error) {
      proxy.$modal.msgError("操作失败: " + error.message)
    }
  }).catch(() => {})
}

/** 恢复工单 */
async function handleResume(row) {
  ElMessageBox.confirm('确定要恢复工单"' + row.workOrderProjectNo + '"吗？', '提示', {
    confirmButtonText: '确认恢复',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(function() {
    const updateData = {
      id: row.id,
      workOrderStatus: "to_finish"
    };
    resumeRepairOrder(updateData);
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("恢复成功")
  }).catch(() => {})
}

/** 撤回工单 */
async function handleRevoke(row) {
  ElMessageBox.confirm('确定要撤回工单"' + row.workOrderProjectNo + '"吗？', '提示', {
    confirmButtonText: '确认撤回',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(function() {
    const updateData = {
      id: row.id,
      workOrderStatus: "to_issue"
    };
    revokeRepairOrder(updateData);
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("撤回成功")
  }).catch(() => {})
}

/** 驳回工单 */
function handleReject(row) {
  approveForm.value = {
    id: row.id,
    approvalStatus: "rejected",
    rejectionReason: ""
  };
  approveDialogVisible.value = true;
}

/** 处理结束操作 */
function handleProcessDone(row) {
  completeForm.value = {
    id: row.id,
    completeDescription: ""
  }
  completeDialogVisible.value = true
}

/** 处理MIS工单编码失去焦点事件 */
function handleMisOrderNoBlur() {
  // 只有当配置为1时才自动获取数据
  if (getMisDataConfig.value === "1" && finalizeForm.value.misOrderNo) {
    // 创建一个只包含必要字段的对象，避免传递repairOrderFlowList等复杂对象
    const requestData = {
      id: finalizeForm.value.id,
      misOrderNo: finalizeForm.value.misOrderNo
    };

    getRepairOrderByMisOrderNo(requestData).then(response => {
      const data = response.data;
      if (data) {
        // 填充开始时间
        if (data.realStartTime) {
          finalizeForm.value.realStartTime = data.realStartTime;
        }

        // 填充结束时间
        if (data.realEndTime) {
          finalizeForm.value.realEndTime = data.realEndTime;
        }

        // 填充检修人员列表
        if (data.workGroupMemberName) {
          finalizeForm.value.workGroupMemberName = data.workGroupMemberName;
        }

        if (data.repairOrderPersonList && data.repairOrderPersonList.length > 0) {
          finalizeForm.value.repairOrderPersonList = data.repairOrderPersonList;
        }
      } else {
        finalizeForm.value.realStartTime = null;
        finalizeForm.value.realEndTime = null;
        finalizeForm.value.workGroupMemberName = null;
        finalizeForm.value.repairOrderPersonList = [];
        proxy.$modal.msgWarning("未找到对应的MIS工单信息");
      }
    }).catch(error => {
      finalizeForm.value.realStartTime = null;
      finalizeForm.value.realEndTime = null;
      finalizeForm.value.workGroupMemberName = null;
      finalizeForm.value.repairOrderPersonList = [];
      proxy.$modal.msgError("获取MIS工单信息失败: " + error.message);
    });
  }
}

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

/** 提交完成 */
async function submitComplete() {
  proxy.$refs["completeFormRef"].validate(async valid => {
    if (valid) {
      try {
        const updateData = {
          id: completeForm.value.id,
          workOrderStatus: "to_be_finalized",
          realEndTime: new Date(),
          completeDescription: completeForm.value.completeDescription
        }

        await processDoneRepairOrder(updateData)

        proxy.$modal.msgSuccess("处理完成，工单进入待结单状态")
        completeDialogVisible.value = false
        getList()
      } catch (error) {
        proxy.$modal.msgError("操作失败: " + error.message)
      }
    }
  })
}

/** 评分操作 */
function handleRating(row) {
  getRepairOrder(row.id).then(response => {
    ratingForm.value = response.data
    ratingForm.value.score = null
    ratingDialogVisible.value = true
  })
}

/** 提交评分 */
async function submitRating() {
  proxy.$refs["ratingFormRef"].validate(async valid => {
    if (valid) {
      try {
        await ratingRepairOrder(ratingForm.value)
        proxy.$modal.msgSuccess("评分成功")
        ratingDialogVisible.value = false
        getList()
      } catch (error) {
        proxy.$modal.msgError("操作失败: " + error.message)
      }
    }
  })
}

/** 查看按钮操作 */
async function handleView(row) {
  try {
    // 获取工单详情
    const response = await getRepairOrder(row.id)
    viewForm.value = response.data
    // 从工单详情中获取流转记录
    flowList.value = response.data.repairOrderFlowList || []
    viewDialogVisible.value = true
  } catch (error) {
    proxy.$modal.msgError("获取工单信息失败: " + error.message)
  }
}

/** 挂起工单 */
function handleSuspend(row) {
  suspendForm.value = row
  suspendForm.value.suspendReason = undefined
  suspendDialogVisible.value = true
}

/** 提交挂起 */
async function submitSuspend() {
  proxy.$refs["suspendFormRef"].validate(async valid => {
    if (valid) {
      try {
        await suspendRepairOrder(suspendForm.value);

        proxy.$modal.msgSuccess("挂起申请已提交");
        suspendDialogVisible.value = false;
        getList();
      } catch (error) {
        proxy.$modal.msgError("挂起申请失败: " + error.message);
      }
    }
  });
}

/** 审批挂起 */
function handleApprove(row) {
  getRepairOrder(row.id).then(response => {
    approveForm.value = response.data
    approveForm.value.approvalStatus = undefined
    approveForm.value.rejectionReason = undefined
    approveDialogVisible.value = true
  })
}

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

/** 提交退回 */
async function submitReturn() {
  proxy.$refs["returnFormRef"].validate(async valid => {
    if (valid) {
      try {
        await returnRepairOrder(returnForm.value);

        proxy.$modal.msgSuccess("退回成功");
        returnDialogVisible.value = false;
        getList();
      } catch (error) {
        proxy.$modal.msgError("退回失败: " + error.message);
      }
    }
  });
}

/** 切换驳回原因显示 */
function toggleRejectionReason() {
  // 驳回原因的必填验证由表单规则控制
}

/** 提交审批 */
async function submitApprove(approvalStatusValue) {
  proxy.$refs["approveFormRef"].validate(async valid => {
    if (valid) {
      try {
        approveForm.value.approvalStatus = approvalStatusValue
        /*if (approveForm.value.approvalStatus === 'approved') {
          approveForm.value.rejectionReason = undefined;
        }*/
        if (approveForm.value.approvalStatus === 'rejected' && !approveForm.value.rejectionReason) {
          proxy.$modal.msgError("驳回时审批意见不能为空");
          return;
        }
        await approveSuspendRepairOrder(approveForm.value);

        proxy.$modal.msgSuccess("操作完成");
        approveDialogVisible.value = false;
        getList();
      } catch (error) {
        proxy.$modal.msgError("操作失败: " + error.message);
      }
    }
  });
}

/** 结单操作 */
function handleFinalize(row) {
  getRepairOrder(row.id).then(response => {
    finalizeForm.value = { ...response.data, selectedMembers: [] }
    // 设置默认维修方式为正常维修(1)
    if (!finalizeForm.value.repairMethod) {
      finalizeForm.value.repairMethod = '1';
    }
    finalizeDialogVisible.value = true
    commonKey++
    /*// 获取场站ID用于查询用户
    finalizeForm.value.pcsStationId = response.data.pcsStationId
    finalizeForm.value.pcsStationPid = response.data.pcsStationPid
    // 根据场站ID查询该场站的用户列表
    if (finalizeForm.value.pcsStationPid) {
      listUser({ pageNum: 1, pageSize: 100, deptId: finalizeForm.value.pcsStationPid }).then(response => {
        userList.value = response.rows
        finalizeDialogVisible.value = true
      })
    }else if (finalizeForm.value.pcsStationId) {
      // 先获取部门信息，判断level是否为4，如果是则查找其父部门直到level为3
      getDeptAndUserByLevel(finalizeForm.value.pcsStationId).then(deptId => {
        // 确保 deptId 是有效的再调用 listUser
        if (deptId) {
          listUser({ pageNum: 1, pageSize: 100, deptId: deptId }).then(response => {
            userList.value = response.rows
            finalizeDialogVisible.value = true
          })
        } else {
          // 如果没有找到有效的部门ID，仍然打开对话框但给出提示
          proxy.$modal.msgWarning("未找到有效的部门信息，无法加载用户列表");
          finalizeDialogVisible.value = true
        }
      })
    } else {
      proxy.$modal.msgWarning("未找到有效的部门信息，无法加载用户列表");
      finalizeDialogVisible.value = true
    }*/
  })
}

/** 提交结单 */
async function submitFinalize() {
  // 根据维修方式执行不同的验证逻辑
  if (finalizeForm.value.repairMethod === '1') {
    // 正常维修需要验证MIS相关字段
    if (!finalizeForm.value.realEndTime) {
      proxy.$modal.msgError("该工单未结束，无法结单！")
      return
    }
  }/* else if (finalizeForm.value.repairMethod === '2') {
    // 复位启机需要验证复位方式
    if (!finalizeForm.value.resetMethod) {
      proxy.$modal.msgError("请选择复位方式！")
      return
    }
  } else {
    proxy.$modal.msgError("请选择维修方式！")
    return
  }*/

  proxy.$refs["finalizeFormRef"].validate(async valid => {
    if (valid) {
      try {
        // 根据维修方式清除不需要的字段
        if (finalizeForm.value.repairMethod === '1') {
          // 正常维修时清除复位方式
          finalizeForm.value.resetMethod = undefined;
        } else if (finalizeForm.value.repairMethod === '2') {
          // 复位启机时清除MIS相关字段
          finalizeForm.value.misOrderNo = undefined;
          finalizeForm.value.realStartTime = undefined;
          finalizeForm.value.realEndTime = undefined;
          finalizeForm.value.workGroupMemberName = undefined;
          finalizeForm.value.repairOrderPersonList = [];
        }

        await finalizeRepairOrder(finalizeForm.value)

        proxy.$modal.msgSuccess("工单结单成功")
        finalizeDialogVisible.value = false
        getList()
      } catch (error) {
        proxy.$modal.msgError("操作失败: " + error.message)
      }
    }
  })
}

/** 检修人员选择变化 */
function handleMembersChange(formName) {
  // 默认使用 acceptForm，但也支持其他表单
  const targetForm = formName === 'finalizeForm' ? finalizeForm : acceptForm;

  // 清空之前的列表
  targetForm.value.repairOrderPersonList = [];
  // 为每个选中的成员创建 GxtRepairOrderPerson 对象
  targetForm.value.selectedMembers.forEach(userId => {
    const user = userList.value.find(u => u.userId === userId)
    if (user) {
      targetForm.value.repairOrderPersonList.push({
        userId: user.userId,
        nickName: user.nickName,
        orderId: targetForm.value.id,
        orderCode: targetForm.value.workOrderProjectNo,
        status: 1
      });
    }
  });
}

/** 复运操作 */
function handleRestart(row) {
  getRepairOrder(row.id).then(response => {
    restartForm.value = response.data
    restartDialogVisible.value = true
  })
}

/** 提交复运 */
async function submitRestart() {
  proxy.$refs["restartFormRef"].validate(async valid => {
    if (valid) {
      try {
        await restartRepairOrder(restartForm.value)

        proxy.$modal.msgSuccess("复运成功")
        restartDialogVisible.value = false
        getList()
      } catch (error) {
        proxy.$modal.msgError("操作失败: " + error.message)
      }
    }
  })
}

function handleImgUplaoded(imgUrl){
    from.value.workUrl = imgUrl;
}

function handleImgRemoved(imgUrl){
    form.value.workUrl = null;
}


/*** MIS导入参数 */
const uploadMis = reactive({
  // 是否显示弹出层（设备导入）
  open: false,
  // 弹出层标题（设备导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的设备数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/gxt/repairOrder/importDataMis"
})

/** 导入按钮操作 */
function handleImportMis() {
  uploadMis.title = "MIS工单导入"
  uploadMis.open = true
  uploadMis.selectedFile = null
}

/** 下载模板操作 */
function importTemplateMis() {
  proxy.download("gxt/repairOrder/importTemplateMis", {
  }, `repairOrderMis_template_${new Date().getTime()}.xlsx`)
}

/**文件上传中处理 */
const handleFileUploadProgressMis = (event, file, fileList) => {
  uploadMis.isUploading = true
}

/** 文件选择处理 */
const handleFileChangeMis = (file, fileList) => {
  uploadMis.selectedFile = file
}

/** 文件删除处理 */
const handleFileRemoveMis = (file, fileList) => {
  uploadMis.selectedFile = null
}

/** 文件上传成功处理 */
const handleFileSuccessMis = (response, file, fileList) => {
  uploadMis.open = false
  uploadMis.isUploading = false
  proxy.$refs["uploadMisRef"].handleRemove(file)
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true })
  getList()
}

/** 提交上传文件 */
function submitFileFormMis() {
  const file = uploadMis.selectedFile
  if (!file || file.length === 0 || !file.name.toLowerCase().endsWith('.xls') && !file.name.toLowerCase().endsWith('.xlsx')) {
    proxy.$modal.msgError("请选择后缀为 “xls”或“xlsx”的文件。")
    return
  }
  proxy.$refs["uploadMisRef"].submit()
}

/*** 维修工单导入参数 */
const upload = reactive({
  // 是否显示弹出层（设备导入）
  open: false,
  // 弹出层标题（设备导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的设备数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/gxt/repairOrder/importData"
})

/** 导入按钮操作 */
function handleImport() {
  upload.title = "维修工单导入"
  upload.open = true
  upload.selectedFile = null
}

/** 下载模板操作 */
function importTemplate() {
  proxy.download("gxt/repairOrder/importTemplate", {
  }, `repairOrder_template_${new Date().getTime()}.xlsx`)
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true
}

/** 文件选择处理 */
const handleFileChange = (file, fileList) => {
  upload.selectedFile = file
}

/** 文件删除处理 */
const handleFileRemove = (file, fileList) => {
  upload.selectedFile = null
}

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false
  upload.isUploading = false
  proxy.$refs["uploadRef"].handleRemove(file)
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true })
  getList()
}

/** 提交上传文件 */
function submitFileForm() {
  const file = upload.selectedFile
  if (!file || file.length === 0 || !file.name.toLowerCase().endsWith('.xls') && !file.name.toLowerCase().endsWith('.xlsx')) {
    proxy.$modal.msgError("请选择后缀为 “xls”或“xlsx”的文件。")
    return
  }
  proxy.$refs["uploadRef"].submit()
}

/** 打开MIS信息选择对话框 */
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
      }
      finalizeForm.value.misOrderNo = row.misNo
      finalizeForm.value.realStartTime = row.realStartTime
      finalizeForm.value.realEndTime = row.realEndTime
      // finalizeForm.value.content = row.content
      listWorkPerson({ misNo: row.misNo }).then(response => {
        debugger
        finalizeForm.value.repairOrderPersonList = response.rows;
        if (finalizeForm.value.repairOrderPersonList) {
          const nickNames = finalizeForm.value.repairOrderPersonList
              .map(person => person.nickName)
              .join(',');
          finalizeForm.value.workGroupMemberName = nickNames
        }
      })
      misInfoSelectVisible.value = false
    })
  }
}

/** 提交作废 */
async function submitInvalidate() {
  proxy.$refs["invalidateFormRef"].validate(async valid => {
    if (!valid) {
      return
    }
    try {
      await invalidateRepairOrder(invalidateForm.value);
      proxy.$modal.msgSuccess("作废成功");
      invalidateDialogVisible.value = false;
      getList();
    } catch (error) {
      proxy.$modal.msgError("操作失败: " + error.message);
    }
  });
}


/** 作废操作 */
function handleInvalidate(row) {
  getRepairOrder(row.id).then(response => {
    invalidateForm.value = { ...response.data }
    invalidateDialogVisible.value = true
  })
}
</script>

<style scoped>
.text-gray-500 {
  color: #6b7280;
}
.mb-2 {
  margin-bottom: 0.5rem;
}
.mb-3 {
  margin-bottom: 0.75rem;
}
.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;
}

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

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

/* MIS工单快速检索样式 */
.quick-select-dropdown {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background: white;
  border: 1px solid #e4e7ed;
  border-top: none;
  border-radius: 0 0 4px 4px;
  max-height: 200px;
  overflow-y: auto;
  z-index: 2000;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.quick-select-item {
  padding: 8px 12px;
  cursor: pointer;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

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

.quick-select-item:last-child {
  border-bottom: none;
}

.mis-no {
  font-weight: bold;
  color: #409eff;
  flex-shrink: 0;
}

.mis-info {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  flex: 1;
  margin-left: 10px;
}

.mis-info .device {
  color: #606266;
  font-size: 12px;
  margin-bottom: 2px;
}

.mis-info .station {
  color: #909399;
  font-size: 11px;
}

.no-data {
  padding: 15px;
  text-align: center;
  color: #909399;
  font-size: 14px;
}

/* 确保表单项有相对定位 */
:deep(.el-form-item) {
  position: relative;
}

/* 输入框样式调整 */
:deep(.el-input-group__append) {
  background-color: #409eff;
  border-color: #409eff;
  color: white;
}

:deep(.el-input-group__append .el-button) {
  color: white;
  border: none;
}

:deep(.el-input-group__append .el-button:hover) {
  background-color: #66b1ff;
}

/* 表单字段间距调整 */
:deep(.el-form-item) {
  margin-bottom: 18px;
}
.content-text {
  white-space: pre-wrap;
  word-break: break-word;
  line-height: 1.5;
}
</style>
