<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
        :key="forceKey"
        v-loading="loading"
        :data="repairOrderList"
        row-key="id"
        @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="下发人" 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="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="workPermitNum"  width="150" :show-overflow-tooltip="true">
        <template #default="scope">
          {{ scope.row.workPermitNum || '-' }}
        </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="repairMethod" min-width="100">-->
<!--        <template #default="scope">-->
<!--          <dict-tag :options="gxt_repair_method" :value="scope.row.repairMethod" />-->
<!--        </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' || scope.row.workOrderStatus === 'accept_return'"
              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' || scope.row.workOrderStatus === 'return'"
              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') && (scope.row.teamLeaderId == userStore.id || userStore.roles.includes('admin'))"
              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 === 'auto_suspend')"
              type="primary"
              link
              @click="handleResume(scope.row)"
              v-hasPermi="['gxt:repairOrder:autoResume']"
          ><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.teamLeaderId == userStore.id || userStore.roles.includes('admin'))"
              type="warning"
              link
              @click="handleReturn(scope.row)"
              v-hasPermi="['gxt:repairOrder:return']"
          ><i class="fa fa-sign-in"></i>退回</el-button> <!--结单退回，负责人退回至班长 -->
          <el-button
              v-if="scope.row.workOrderStatus === 'return'|| scope.row.workOrderStatus === 'assigned'"
              type="warning"
              link
              @click="handleReturn(scope.row)"
              v-hasPermi="['gxt:repairOrder:acceptReturn']"
          ><i class="fa fa-sign-in"></i>退回</el-button> <!--接单退回，班长退回至下发环节 -->
          <!--          <el-button
                      v-if="scope.row.workOrderStatus === '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, '1')"-->
<!--              v-hasPermi="['gxt:repairOrder:finalize']"-->
<!--          ><i class="fa fa-check"></i>结单</el-button>-->
          <el-button
              v-if="scope.row.workOrderStatus === 'to_finish'"
              type="success"
              link
              @click="handleFinalize(scope.row, '1')"
              v-hasPermi="['gxt:repairOrder:finalize']"
          ><i class="fa fa-check"></i>结单</el-button>
          <el-button
              v-if="scope.row.workOrderStatus === 'to_finish'"
              type="primary"
              link
              @click="handleReset(scope.row)"
              v-hasPermi="['gxt:repairOrder:finalize']"
          ><i class="fa fa-refresh"></i>复启</el-button>
          <el-button
              v-if="scope.row.workOrderStatus === 'to_approve'"
              type="primary"
              link
              @click="handleApprove(scope.row)"
              v-hasPermi="['gxt:repairOrder:approve']"
          ><i class="fa fa-check-circle"></i>审批</el-button>
          <!--          <el-button
                      v-if="scope.row.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.restartTime == null && scope.row.workOrderStatus != 'to_issue' && scope.row.workOrderStatus != 'auto_suspend' && scope.row.workOrderStatus != 'accept_return'"
              type="success"
              link
              @click="handleRestart(scope.row)"
              v-hasPermi="['gxt:repairOrder:restart']"
          ><i class="fa fa-refresh"></i>复运</el-button>
          <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="故障代码">
              <el-input
                  v-model="form.faultCode"
                  placeholder="请输入故障代码或点击选择"
                  maxlength="20"
                  show-word-limit
                  clearable
                  @focus="handleFaultCodeInputFocus"
                  @blur="handleFaultCodeInputBlur"
                  @input="handleFaultCodeInput"
                  @clear="handleFaultCodeClear"
              />
              <!-- 故障代码快速检索下拉框 -->
              <div class="quick-select-dropdown" v-show="showFaultCodeQuickSelect && quickFaultInfoList.length > 0">
                <div
                    v-for="item in quickFaultInfoList"
                    :key="item.id"
                    class="quick-select-item"
                    @click="handleFaultCodeQuickSelect(item)">
                  <span class="user-name">{{ item.faultCode }}</span>
                  <span class="user-name">{{ item.faultBarcode }}</span>
                </div>
              </div>
              <div class="quick-select-dropdown no-data" v-show="showFaultCodeQuickSelect && quickFaultInfoList.length === 0 && form.faultCode && !faultInfoLoading">
                <div>未找到匹配的故障代码</div>
              </div>
              <div class="quick-select-dropdown no-data" v-show="showFaultCodeQuickSelect && faultInfoLoading">
                <div>
                  <i class="el-icon-loading"></i>
                  搜索中...
                </div>
              </div>
            </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"
                  placeholder="请输入故障条文或点击选择"
                  show-word-limit
                  clearable
                  @focus="handleFaultBarcodeInputFocus"
                  @blur="handleFaultBarcodeInputBlur"
                  @input="handleFaultBarcodeInput"
                  @clear="handleFaultBarcodeClear"
              />
              <!-- 故障条文快速检索下拉框 -->
              <div class="quick-select-dropdown" v-show="showFaultBarcodeQuickSelect && quickFaultBarcodeList.length > 0">
                <div
                    v-for="item in quickFaultBarcodeList"
                    :key="item.id"
                    class="quick-select-item"
                    @click="handleFaultBarcodeQuickSelect(item)">
                  <span class="user-name">{{ item.faultBarcode }}</span>
                  <span class="user-name">{{ item.faultCode }}</span>
                </div>
              </div>
              <div class="quick-select-dropdown no-data" v-show="showFaultBarcodeQuickSelect && quickFaultBarcodeList.length === 0 && form.faultBarcode && !faultBarcodeLoading">
                <div>未找到匹配的故障条文</div>
              </div>
              <div class="quick-select-dropdown no-data" v-show="showFaultBarcodeQuickSelect && faultBarcodeLoading">
                <div>
                  <i class="el-icon-loading"></i>
                  搜索中...
                </div>
              </div>
            </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="100"
                  show-word-limit
                  :rows="3"
                  clearable
                  @focus="handleFaultDescInputFocus"
                  @blur="handleFaultDescInputBlur"
                  @input="handleFaultDescInput"
                  @clear="handleFaultDescClear"
              />
              <!-- 故障描述快速检索下拉框 -->
              <div class="quick-select-dropdown" v-show="showFaultDescQuickSelect && quickFaultDescList.length > 0">
                <div
                    v-for="item in quickFaultDescList"
                    :key="item.id"
                    class="quick-select-item"
                    @click="handleFaultDescQuickSelect(item)">
                  <span class="user-name">{{ item.faultCode }}</span>
                  <span class="user-name">{{ item.faultBarcode }}</span>
                </div>
              </div>
              <div class="quick-select-dropdown no-data" v-show="showFaultDescQuickSelect && quickFaultDescList.length === 0 && form.faultDesc && !faultDescLoading">
                <div>未找到匹配的故障描述</div>
              </div>
              <div class="quick-select-dropdown no-data" v-show="showFaultDescQuickSelect && faultDescLoading">
                <div>
                  <i class="el-icon-loading"></i>
                  搜索中...
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-col :span="24">
          <el-form-item label="附件（可选）">
            <preview :limit="8" v-model="form.orderAttachment" :filesize="5"></preview>
          </el-form-item>
        </el-col>
<!--        <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="showExportFieldsDialog" width="600px" append-to-body>
       <div style="position: absolute;bottom: 65px;right: 38%;">
        <el-button type="primary" icon="upload" size="mini" style="width:5px;" @click="upDown('up')" /><br/>
        <el-button type="primary" icon="download" size="mini" style="margin-top:3px;width:5px;" @click="upDown('down')" />
      </div>
      <el-transfer
          v-model="exportFieldsSelected"
          :data="exportFieldsData"
          :titles="['可选字段', '导出字段']"
          target-order = "push"
          show-checkbox
          filterable
          filter-placeholder="请输入字段名称"
          @right-check-change="rightCheckHandler">
      </el-transfer>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showExportFieldsDialog = false">取 消</el-button>
          <el-button type="primary" @click="confirmExport">确 定</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="12">
            <el-form-item label="故障条文"><el-input v-model="acceptForm.faultBarcode" disabled /></el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="故障描述">
              <el-input
                  v-model="acceptForm.faultDesc"
                  type="textarea"
                  :rows="3"
                  :disabled="isFaultDesc"
              />
            </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>

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

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

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

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

    <!-- 评分对话框 -->
    <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" v-if="restartForm.infoEntry == '1'">
            <el-form-item label="MIS工单编码"><el-input v-model="restartForm.misOrderNo" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12" v-if="restartForm.infoEntry == '2'">
            <el-form-item label="工作票编号">
              <el-input v-model="restartForm.workPermitNum" disabled />
            </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-col :span="12">
            <el-form-item label="损失电量（kWh）" prop="lostPower">
              <el-input-number
                  v-model="restartForm.lostPower"
                  placeholder="请输入损失电量"
                  controls-position="right"
                  style="width: 100%"
                  class="input-number-left"
                  :min="0"
              />
            </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>

    <!-- 查看工单详情对话框 -->
    <ViewDialog
        v-model="viewDialogVisible"
        :data="viewForm"
        :work-order-status-options="gxt_work_order_status"
        :reset-method-options="gxt_reset_method"
        :repair-order-flow-action-type-options="gxt_repair_order_flow_action_type"
        :work-area-options="gxt_work_area"
        :return-type-options="gxt_return_type"
        :accept-return-type-options="gxt_accept_return_type"
        :finalize-method-options="gxt_finalize_method"
    />

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

    <!-- 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,
  getExportFields
} 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, listUserData, listUserNoPermi, listLeader} 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 {genPostCode} from "@/api/system/autocode/rule.js";
import MisInfoSelectSingle from "@/components/misInfoSelect/single.vue";
import {listAutoMisInfo, listMisInfo, listWorkPerson} from "@/api/gxt/misInfo.js";
import {listGxtOrder} from "@/api/gxt/gxtOrder.js";
import useUserStore from '@/store/modules/user'
import { useRoute } from 'vue-router'
import { watch } from 'vue'
import { decryptParams } from '@/utils/encrypt'
import ResetDialog from '@/components/repairOrder/reset.vue'
import FinalizeDialog from '@/components/repairOrder/finalize.vue'
import ReturnDialog from '@/components/repairOrder/return.vue'
import SuspendDialog from '@/components/repairOrder/suspend.vue'
import ViewDialog from '@/components/repairOrder/view.vue'
import ApproveDialog from '@/components/repairOrder/approve.vue'
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,gxt_info_entry,gxt_work_area, gxt_accept_return_type,gxt_finalize_method }
    = 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","gxt_info_entry","gxt_work_area","gxt_accept_return_type","gxt_finalize_method")

// 数据列表相关
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 showExportFieldsDialog = ref(false)
const exportFieldsSelected = ref([])
const exportFieldsData = 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)
// 初始化禁用状态为 false（单选框默认可用）
const infoEntryDisabled = ref(false);

// 各种表单数据
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: [],
  infoEntry: null,
  workArea: []
})
const invalidateForm = ref({}) // 添加作废表单
const ratingForm = ref({
  score: null
})
const startForm = ref({})  // 添加开始处理表单数据
const restartForm = ref({
  realEndTime: null,
  lostPower: 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 resetDialogVisible = 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 showFaultCodeQuickSelect = ref(false)
const showFaultBarcodeQuickSelect = ref(false)
const showFaultDescQuickSelect = ref(false)
const quickFaultInfoList = ref([])
const quickFaultBarcodeList = ref([])
const quickFaultDescList = ref([])
const faultInfoLoading = ref(false)
const faultBarcodeLoading = ref(false)
const faultDescLoading = ref(false)
const faultInfoSearchTimer = ref(null)
const faultBarcodeSearchTimer = ref(null)
const faultDescSearchTimer = ref(null)
const allFaultInfoList = ref([]) // 存储所有故障数据用于快速检索

const forceKey = ref(0)

const userStore = useUserStore();


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

const disabledStartDate = (time) => {
  const getYYYYMMDD = (date) => {
    const y = date.getFullYear();
    const m = String(date.getMonth() + 1).padStart(2, '0');
    const d = String(date.getDate()).padStart(2, '0');
    return `${y}-${m}-${d}`;
  };

  const today = getYYYYMMDD(new Date());

  let acceptDateStr = null;
  const acceptStr = finalizeForm.value.acceptTime; // 脚本中用 .value
  if (acceptStr) {
    // 假设 acceptTime 格式是 "2025-12-09 18:01"，取前面日期部分
    acceptDateStr = acceptStr.split(' ')[0]; // 得到 "2025-12-09"
  }

  const selectedDateStr = getYYYYMMDD(time);

  // 如果没有 acceptTime，只禁用未来日期
  if (!acceptDateStr) {
    return selectedDateStr > today;
  }

  // 禁用：早于 acceptDate 或 晚于今天
  return selectedDateStr < acceptDateStr || selectedDateStr > today;
};

const disabledEndDate = (time) => {
  const getYYYYMMDD = (date) => {
    const y = date.getFullYear();
    const m = String(date.getMonth() + 1).padStart(2, '0');
    const d = String(date.getDate()).padStart(2, '0');
    return `${y}-${m}-${d}`;
  };

  const today = getYYYYMMDD(new Date());

  let acceptDateStr = null;
  const acceptStr = finalizeForm.value.acceptTime; // 脚本中用 .value
  const startStr = finalizeForm.value.realStartTime;
  if (startStr) {
    // 假设 acceptTime 格式是 "2025-12-09 18:01"，取前面日期部分
    acceptDateStr = startStr.split(' ')[0]; // 得到 "2025-12-09"
  } else if(acceptStr) {
    acceptDateStr = acceptStr.split(' ')[0];
  }

  const selectedDateStr = getYYYYMMDD(time);

  // 如果没有 acceptTime，只禁用未来日期
  if (!acceptDateStr) {
    return selectedDateStr > today;
  }

  // 禁用：早于 acceptDate 或 晚于今天
  return selectedDateStr < acceptDateStr || selectedDateStr > today;
};

const 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 listLeader({
      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 listLeader({
      deptId: -1, // 通过后台配置部门
      status: '0'
    })
    allUserList.value = response.data || []
    quickTeamLeaderList.value = allUserList.value;
  } catch (error) {
    console.error('加载工作负责人列表失败:', error)
    allUserList.value = []
  } finally {
    teamLeaderLoading.value = false
  }
}

/** 快速选择工作负责人 */
const handleTeamLeaderQuickSelect = (item) => {
  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)
}

/** 加载所有故障信息列表 */
const loadAllFaultInfoList = async () => {
  try {
    // 构建查询参数，包含风机编号和场站信息
    const queryParams = {
      pageNum: 1,
      pageSize: 1000, // 获取所有故障代码
      isActive: 0
    };

    // 如果表单中有风机编号和场站信息，则添加到查询参数中
    if (form.value.pcsDeviceName) {
      queryParams.model = form.value.model;
    }
    if (form.value.pcsStationName) {
      queryParams.station = form.value.pcsStationName;
    }

    // 加载故障代码数据
    const response = await listFaultCodes(queryParams);
    allFaultInfoList.value = response.rows || [];
  } catch (error) {
    console.error('加载故障信息列表失败:', error);
    allFaultInfoList.value = [];
  }
}

// 故障代码快速检索方法
/** 故障代码输入框获取焦点 */
const handleFaultCodeInputFocus = async () => {
  showFaultCodeQuickSelect.value = true;

  // 加载所有故障信息
  await loadAllFaultInfoList();

  // 如果已有输入内容，立即搜索
  if (form.value.faultCode && form.value.faultCode.trim()) {
    handleFaultCodeInput(form.value.faultCode);
  } else {
    // 如果没有输入内容，显示所有故障信息
    quickFaultInfoList.value = allFaultInfoList.value;
  }
};

/** 故障代码输入框失去焦点 */
const handleFaultCodeInputBlur = () => {
  // 延迟隐藏下拉框，确保点击选项能触发
  setTimeout(() => {
    showFaultCodeQuickSelect.value = false;
  }, 200);
};

/** 故障代码输入事件 - 实时搜索 */
const handleFaultCodeInput = (value) => {
  const searchText = value.trim();

  if (!searchText) {
    quickFaultInfoList.value = [];
    showFaultCodeQuickSelect.value = false;
    return;
  }

  showFaultCodeQuickSelect.value = true;

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

  // 过滤故障信息列表
  const lowerKeyword = searchText.toLowerCase();
  quickFaultInfoList.value = allFaultInfoList.value.filter(item =>
    (item.faultCode && item.faultCode.toLowerCase().includes(lowerKeyword)) ||
    (item.faultBarcode && item.faultBarcode.toLowerCase().includes(lowerKeyword)) ||
    (item.faultDescription && item.faultDescription.toLowerCase().includes(lowerKeyword))
  );

  // 设置新的定时器，防抖处理（500ms）
  faultInfoSearchTimer.value = setTimeout(() => {
    // 由于我们已经在上面过滤了，这里不需要额外的API调用
  }, 500);
};

/** 快速选择故障代码 */
const handleFaultCodeQuickSelect = (item) => {
  form.value.faultCode = item.faultCode;
  form.value.faultBarcode = item.faultBarcode;
  form.value.faultDesc = item.faultDescription;
  showFaultCodeQuickSelect.value = false;
};

/** 清空故障代码 */
const handleFaultCodeClear = () => {
  form.value.faultCode = '';
  form.value.faultBarcode = '';
  form.value.faultDesc = '';
  quickFaultInfoList.value = [];
  showFaultCodeQuickSelect.value = false;
};

// 故障条文快速检索方法
/** 故障条文输入框获取焦点 */
const handleFaultBarcodeInputFocus = async () => {
  showFaultBarcodeQuickSelect.value = true;

  // 加载所有故障信息
  await loadAllFaultInfoList();

  // 如果已有输入内容，立即搜索
  if (form.value.faultBarcode && form.value.faultBarcode.trim()) {
    handleFaultBarcodeInput(form.value.faultBarcode);
  } else {
    // 如果没有输入内容，显示所有故障信息
    quickFaultBarcodeList.value = allFaultInfoList.value;
  }
};

/** 故障条文输入框失去焦点 */
const handleFaultBarcodeInputBlur = () => {
  // 延迟隐藏下拉框，确保点击选项能触发
  setTimeout(() => {
    showFaultBarcodeQuickSelect.value = false;
  }, 200);
};

/** 故障条文输入事件 - 实时搜索 */
const handleFaultBarcodeInput = (value) => {
  const searchText = value.trim();

  if (!searchText) {
    quickFaultBarcodeList.value = [];
    showFaultBarcodeQuickSelect.value = false;
    return;
  }

  showFaultBarcodeQuickSelect.value = true;

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

  // 过滤故障信息列表
  const lowerKeyword = searchText.toLowerCase();
  quickFaultBarcodeList.value = allFaultInfoList.value.filter(item =>
    (item.faultCode && item.faultCode.toLowerCase().includes(lowerKeyword)) ||
    (item.faultBarcode && item.faultBarcode.toLowerCase().includes(lowerKeyword)) ||
    (item.faultDescription && item.faultDescription.toLowerCase().includes(lowerKeyword))
  );

  // 设置新的定时器，防抖处理（500ms）
  faultBarcodeSearchTimer.value = setTimeout(() => {
    // 由于我们已经在上面过滤了，这里不需要额外的API调用
  }, 500);
};

/** 快速选择故障条文 */
const handleFaultBarcodeQuickSelect = (item) => {
  form.value.faultCode = item.faultCode;
  form.value.faultBarcode = item.faultBarcode;
  form.value.faultDesc = item.faultDescription;
  showFaultBarcodeQuickSelect.value = false;
};

/** 清空故障条文 */
const handleFaultBarcodeClear = () => {
  form.value.faultCode = '';
  form.value.faultBarcode = '';
  form.value.faultDesc = '';
  quickFaultBarcodeList.value = [];
  showFaultBarcodeQuickSelect.value = false;
};

// 故障描述快速检索方法
/** 故障描述输入框获取焦点 */
const handleFaultDescInputFocus = async () => {
  showFaultDescQuickSelect.value = true;

  // 加载所有故障信息
  await loadAllFaultInfoList();

  // 如果已有输入内容，立即搜索
  if (form.value.faultDesc && form.value.faultDesc.trim()) {
    handleFaultDescInput(form.value.faultDesc);
  } else {
    // 如果没有输入内容，显示所有故障信息
    quickFaultDescList.value = allFaultInfoList.value;
  }
};

/** 故障描述输入框失去焦点 */
const handleFaultDescInputBlur = () => {
  // 延迟隐藏下拉框，确保点击选项能触发
  setTimeout(() => {
    showFaultDescQuickSelect.value = false;
  }, 200);
};

/** 故障描述输入事件 - 实时搜索 */
const handleFaultDescInput = (value) => {
  const searchText = value.trim();

  if (!searchText) {
    quickFaultDescList.value = [];
    showFaultDescQuickSelect.value = false;
    return;
  }

  showFaultDescQuickSelect.value = true;

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

  // 过滤故障信息列表
  const lowerKeyword = searchText.toLowerCase();
  quickFaultDescList.value = allFaultInfoList.value.filter(item =>
    (item.faultCode && item.faultCode.toLowerCase().includes(lowerKeyword)) ||
    (item.faultBarcode && item.faultBarcode.toLowerCase().includes(lowerKeyword)) ||
    (item.faultDescription && item.faultDescription.toLowerCase().includes(lowerKeyword))
  );

  // 设置新的定时器，防抖处理（500ms）
  faultDescSearchTimer.value = setTimeout(() => {
    // 由于我们已经在上面过滤了，这里不需要额外的API调用
  }, 500);
};

/** 快速选择故障描述 */
const handleFaultDescQuickSelect = (item) => {
  form.value.faultCode = item.faultCode;
  form.value.faultBarcode = item.faultBarcode;
  form.value.faultDesc = item.faultDescription;
  showFaultDescQuickSelect.value = false;
};

/** 清空故障描述 */
const handleFaultDescClear = () => {
  form.value.faultCode = '';
  form.value.faultBarcode = '';
  form.value.faultDesc = '';
  quickFaultDescList.value = [];
  showFaultDescQuickSelect.value = false;
};

/** 搜索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,
  outTimeParam: null,
})

// 表单验证规则
const rules = ref({
  // workOrderProjectNo: [
  //   { required: true, message: "工单编码不能为空", trigger: "blur" }
  // ],
  pcsDeviceName: [
    { required: true, message: "风机编号不能为空", trigger: "change" }
  ],
  /*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: "change" }
  ],
  faultCode: [
    { required: true, message: "故障代码不能为空", trigger: "change" }
  ],
})

// 接单表单验证规则
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 resetRules = ref({
  resetMethod: [
    { required: true, message: "请选择复位方式", trigger: "change" }
  ]
})

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

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

// 作废表单验证规则
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({
  lostPower: [
    { required: true, message: "损失电量不能为空", trigger: "change" }
  ],
  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 getFromRoute() {
  // 检查是否从月度工分汇总页面跳转而来，如果有工单编号则自动筛选
  const fromRoute = sessionStorage.getItem('fromRouteRepair');
  const workOrderNo = sessionStorage.getItem('workOrderProjectNoRepair');
  if (fromRoute === '/workScore/monthScore' && workOrderNo) {
    // 更新查询参数
    queryParams.value.workOrderProjectNo = workOrderNo;
    listRepairOrder(queryParams.value).then(response => {
      if(response.rows && response.rows.length > 0) {
        handleView(response.rows[0]);
      }
    })
    // 清除sessionStorage中的临时数据
    sessionStorage.removeItem('fromRouteRepair');
    sessionStorage.removeItem('workOrderProjectNoRepair');
  }
}

// 监听窗口大小变化
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")
}

// 解析路由参数的函数
function parseRouteParams(route) {
  // 只有当路由参数存在时才更新，避免覆盖已有的查询条件
  if (route.query.data) {
    // 解密参数
    const decryptedParams = decryptParams(route.query.data);
    if (decryptedParams.timeOutNum !== undefined) {
      queryParams.value.outTimeParam = decryptedParams.timeOutNum;
    }
    if (decryptedParams.workOrderStatus !== undefined) {
      queryParams.value.workOrderStatus = decryptedParams.workOrderStatus;
    }
    if (decryptedParams.userType !== undefined) {
      queryParams.value.homePageParam = decryptedParams.userType;
    }
  } else {
    // 为了向后兼容，也支持原始的参数传递方式
    if (route.query.timeOutNum !== undefined) {
      queryParams.value.outTimeParam = route.query.timeOutNum;
    }
    if (route.query.workOrderStatus !== undefined) {
      queryParams.value.workOrderStatus = route.query.workOrderStatus;
    }
  }

  // 确保分页参数正确设置
  if (!queryParams.value.pageNum) {
    queryParams.value.pageNum = 1;
  }
  if (!queryParams.value.pageSize) {
    queryParams.value.pageSize = 10;
  }
}

onMounted(() => {
  // 从路由参数中获取值
  const route = useRoute();
  parseRouteParams(route);

  getList()
  getMaintenanceCenterAndStationList()
  getFaultCodeList()
  getGetMisDataConfig() // 获取配置参数
  getExportFieldsData() // 获取导出字段数据
  window.addEventListener('resize', handleResize)
  getFromRoute()
})

// 监听风机编号和场站变化，自动刷新故障信息列表
// 监听风机编号变化，清空故障相关字段
watch(() => form.value.pcsDeviceName, (newDeviceName, oldDeviceName) => {
  if (newDeviceName !== oldDeviceName) {
    // 清空故障相关字段，因为新设备可能需要选择不同的故障信息
    form.value.faultCode = '';
    form.value.faultBarcode = '';
    form.value.faultDesc = '';

    // 同时清空故障信息列表，以便下次获取焦点时使用新的设备信息重新加载
    allFaultInfoList.value = [];
  }
}, { immediate: false });

// 监听路由变化，当从其他路由跳转到当前路由时重新解析参数
const route = useRoute();
watch(() => route.query, (newQuery, oldQuery) => {
  // 当路由查询参数发生变化时，重新解析参数
  parseRouteParams(route);

  // 重新获取列表数据
  getList();
  getFromRoute()
}, { deep: true });

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 => {
    console.log(response.rows);
    repairOrderList.value = response.rows
    total.value = response.total
    loading.value = false
    forceKey.value += 1
  })
}

/** 查询维保中心和场站列表 */
/*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 resetTimeOutOrder() {
  if (queryParams.value.outTimeParam != null) {
    queryParams.value.outTimeParam = null;
    queryParams.value.workOrderStatus = null;
    queryParams.value.userType = null;
  }
}

// 表单重置
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
    handleAutoGenChange()
  }
  equipmentSelectVisible.value = false
}

/** 重置按钮操作 */
function resetQuery() {
  resetTimeOutOrder();
  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()
  openDialog.value = true
  dialogTitle.value = "新建维修工单"
  optType.value = "add"
}

/** 修改按钮操作 */
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
          resetTimeOutOrder();
          getList()
        })
      } else {
        addRepairOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("新建成功")
          openDialog.value = false
          resetTimeOutOrder();
          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
          resetTimeOutOrder();
          getList()
        })
      } else {
        addRepairOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("新建成功")
          openDialog.value = false
          resetTimeOutOrder();
          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(() => {
    resetTimeOutOrder();
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  // 显示字段选择对话框
  showExportFieldsDialog.value = true;

  // 定义默认选中的字段（基于字段标签）
  const defaultSelectedLabels = [
    '工单编码',
    '风机编号',
    '工单状态',
    '维保中心',
    '场站',
    '品牌',
    '机型',
    '发生时间',
    '工作负责人',
    '开始时间',
    '结束时间',
  ];

  // 在导出字段中查找对应的key
  const selectedKeys = [];
  exportFieldsData.value.forEach(field => {
    if (defaultSelectedLabels.includes(field.label)) {
      selectedKeys.push(field.key);
    }
  });

  // 设置默认选中的字段
  exportFieldsSelected.value = selectedKeys;
}

/** 确认导出 */
function confirmExport() {
  if (exportFieldsSelected.value.length === 0) {
    proxy.$modal.msgWarning("请至少选择一个导出字段");
    return;
  }

  // 将导出字段拼接成字符串
  const exportFieldsStr = exportFieldsSelected.value.join(',');

  const exportParams = {
    ...queryParams.value,
    exportFields: exportFieldsStr
  };

  proxy.download('gxt/repairOrder/export', exportParams, `repairOrder_${new Date().getTime()}.xlsx`);

  showExportFieldsDialog.value = false;
}

/** 故障代码变化处理 */
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

    // 自动回填故障代码、故障条文、故障描述
    if (response.data.faultCode) {
      assignForm.value.faultCode = response.data.faultCode;
    }
    if (response.data.faultBarcode) {
      assignForm.value.faultBarcode = response.data.faultBarcode;
    }
    if (response.data.faultDesc) {
      assignForm.value.faultDesc = response.data.faultDesc;
    }
  })
}

/** 关联维保工单变化处理 */
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
        resetTimeOutOrder();
        getList()
      } catch (error) {
        proxy.$modal.msgError("下发失败: " + error.message)
      }
    }
  })
}

const isFaultDesc = ref(true)
/** 接单操作 */
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 = [];
    }
    if (acceptForm.value.faultDesc == '') {
      isFaultDesc.value = false
    } else {
      isFaultDesc.value = true
    }
    // 预加载工作负责人列表
    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
        resetTimeOutOrder();
        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(() => {
    resetTimeOutOrder();
    getList()
    proxy.$modal.msgSuccess("恢复成功")
  }).catch(() => {})
}

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

    proxy.$modal.msgSuccess("工单已开始处理");
    startDialogVisible.value = false;
    resetTimeOutOrder();
    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("工单已暂停")
      resetTimeOutOrder();
      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: row.workOrderStatus == 'auto_suspend'? 'assigned' : 'to_finish'
    };
    resumeRepairOrder(updateData);
  }).then(() => {
    resetTimeOutOrder();
    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(() => {
    resetTimeOutOrder();
    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
        resetTimeOutOrder();
        getList()
      } catch (error) {
        proxy.$modal.msgError("操作失败: " + error.message)
      }
    }
  })
}

/** 获取导出字段数据 */
function getExportFieldsData() {
  getExportFields().then(response => {
    exportFieldsData.value = response.data;
  });
}

/** 评分操作 */
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
        resetTimeOutOrder();
        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;
        resetTimeOutOrder();
        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
    // 打开对话框后重置表单验证错误
    proxy.resetForm("approveFormRef")
  })
}

/** 退回 */
function handleReturn(row) {
  getRepairOrder(row.id).then(response => {
    returnForm.value = response.data
    if (row.workOrderStatus == 'to_finish') {
      returnForm.value.returnType = '1'
      returnForm.value.returnReason = undefined
    } else {
      returnForm.value.acceptReturnType = undefined
      returnForm.value.acceptReturnReason = undefined
    }
    // }
    returnDialogVisible.value = true
    // proxy.resetForm("returnFormRef")
  })
}

/** 提交退回 */
async function submitReturn() {
  proxy.$refs["returnFormRef"].validate(async valid => {
    if (valid) {
      try {
        if (returnForm.value.workOrderStatus == 'return' || returnForm.value.workOrderStatus == 'assigned') {
          returnForm.value.workOrderStatus = "accept_return";
        } else {
          returnForm.value.workOrderStatus = "return";
        }
        await returnRepairOrder(returnForm.value);

        proxy.$modal.msgSuccess("退回成功");
        returnDialogVisible.value = false;
        resetTimeOutOrder();
        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;
        resetTimeOutOrder();
        getList();
      } catch (error) {
        proxy.$modal.msgError("操作失败: " + error.message);
      }
    }
  });
}

/** 结单操作 */
function handleFinalize(row, method) {
  // getRepairOrder(row.id).then(response => {
  //   finalizeFormData.value = { ...response.data, selectedMembers: [] }
  //   debugger
  //   finalizeFormData.value.repairMethod = method;
  //   if (method == '1') {
  //     finalizeFormData.value.infoEntry = '1'
  //   }
  //   finalizeDialogVisible.value = true
  //   commonKey++
  // })
  finalizeFormData.value = row
  finalizeFormData.value.orderId = row.id
  finalizeFormData.value.infoEntry = '1'
  finalizeFormData.value.repairMethod = method;
  debugger
  if (row.occurTime && row.restartTime) {
    listAutoMisInfo({
      pauseTime: row.occurTime,
      restartTime: row.restartTime,
      pcsDeviceName: row.pcsDeviceName,
      pcsStationName: row.pcsStationName,
      workOrderStatus: '结束'
    }).then(response => {
      const misInfo = response.rows
      debugger
      // finishDialogVisible.value = true
      if (misInfo.length > 0 && misInfo.length == 1) {
        // 有工作票号提示
        if (misInfo[0].workPermitNum) {
          // 查询MIS工单是否已存在
          listRepairOrder({pageNum: 1, pageSize: 10, misOrderNo: misInfo[0].misNo }).then(response => {
            const gxtOrders = response.rows
            if (gxtOrders.length == 0) {
              finalizeFormData.value.misOrderNo = misInfo[0].misNo
              finalizeFormData.value.realStartTime = misInfo[0].realStartTime
              finalizeFormData.value.realEndTime = misInfo[0].realEndTime
              finalizeFormData.value.workPermitNum = misInfo[0].workPermitNum
              listWorkPerson({misNo: misInfo[0].misNo}).then(response => {
                finalizeFormData.value.repairOrderPersonList = response.rows;
                if (finalizeFormData.value.repairOrderPersonList) {
                  // 查询负责人信息并回填
                  for (const person of finalizeFormData.value.repairOrderPersonList) {
                    // 严格判断isLeader为1（兼容数字/字符串类型）
                    if (person.isLeader === 1 || person.isLeader === '1') {
                      finalizeFormData.value.teamLeaderName = person.nickName;
                      break; // 找到后立即停止循环
                    }
                  }
                  const nickNames = finalizeFormData.value.repairOrderPersonList
                      .map(person => person.nickName)
                      .join(',');
                  finalizeFormData.value.workGroupMemberName = nickNames
                  // finishDialogVisible.value = true
                }
              })
            } else {
              ElMessageBox.confirm('未找到匹配的MIS工单，请确认风机停复机时间是否已录入工效通系统或请进入工作票录入方式。', '提示', {
                confirmButtonText: '确定',
                showCancelButton: false,
                type: 'warning'
              }).then(function() {
                // finalizeFormData.value.infoEntry = '2'
                infoEntryDisabled.value = true
              }).then(() => {
              }).catch(() => {})
            }
          })
        } else {  // 无工作票号提示
          ElMessageBox.confirm('已匹配到MIS工单，但未关联工作票号，系统无法自动结单，请进入工作票录入方式。', '提示', {
            confirmButtonText: '确定',
            showCancelButton: false,
            type: 'warning'
          }).then(function() {
            // finalizeFormData.value.infoEntry = '2'
            infoEntryDisabled.value = true
          }).then(() => {
          }).catch(() => {})
        }

      } else if (misInfo.length == 0) {
        ElMessageBox.confirm('未找到匹配的MIS工单，请确认风机停复机时间是否已录入工效通系统或请进入工作票录入方式。', '提示', {
          confirmButtonText: '确定',
          showCancelButton: false,
          type: 'warning'
        }).then(function() {
          // finalizeFormData.value.infoEntry = '2'
          infoEntryDisabled.value = true
        }).then(() => {
        }).catch(() => {})
      } else if (misInfo.length > 1) {
        infoEntryDisabled.value = false
      }
    })
  } else {
    // finishDialogVisible.value = true
    ElMessageBox.confirm('未找到匹配的MIS工单，请确认风机停复机时间是否已录入工效通系统或请进入工作票录入方式。', '提示', {
      confirmButtonText: '确定',
      showCancelButton: false,
      type: 'warning'
    }).then(function() {
      debugger
      // finalizeFormData.value.infoEntry = '2'
      infoEntryDisabled.value = true
    }).then(() => {
    }).catch(() => {})
    finalizeFormData.value.workPermitNum = null
    finalizeFormData.value.misNo = null
  }
  finalizeDialogVisible.value = true
  commonKey++
}

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

// 添加响应式数据用于复启组件
const resetFormData = ref({})

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

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

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

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

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



/** 提交复启 */
async function submitReset() {
  proxy.$refs["resetFormRef"].validate(async valid => {
    if (valid) {
      try {
        finalizeForm.value.repairMethod = '2';
        await finalizeRepairOrder(finalizeForm.value)
        proxy.$modal.msgSuccess("复启成功")
        resetDialogVisible.value = false
        resetTimeOutOrder();
        getList()
      } catch (error) {
        proxy.$modal.msgError("操作失败: " + error.message)
      }
    }
  })
}

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

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

// 用于传递给挂起组件的提交方法
async function submitSuspendFromParent(data) {
  await suspendRepairOrder(data)
}

// 在提交审批成功后的回调函数
async function submitApproveFromParent(data) {
  await approveSuspendRepairOrder(data)
}

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

// 在提交审批成功后的回调函数
function handleApproveSuccess() {
  approveDialogVisible.value = false
  resetTimeOutOrder()
  getList()
}
/** 工作班成员选择变化 */
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 {
        // 判断 restartTime 是否小于 realEndTime
        if (new Date(restartForm.value.restartTime) < new Date(restartForm.value.realEndTime)) {
          // 如果是，弹出确认对话框
          const confirmResult = await proxy.$confirm('复运时间早于实际结束时间，是否继续？', '警告', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).catch(() => {
            // 如果用户点击了取消按钮，这里会捕获到错误并返回
            return false;
          });

          // 如果用户点击了取消按钮，终止操作
          if (!confirmResult) {
            return;
          }
        }

        await restartRepairOrder(restartForm.value)

        proxy.$modal.msgSuccess("复运成功")
        restartDialogVisible.value = false
        resetTimeOutOrder();
        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 })
  resetTimeOutOrder();
  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 })
  resetTimeOutOrder();
  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
      }
      // 使用展开运算符创建新对象以确保响应式更新
      finalizeFormData.value = {
        ...finalizeFormData.value,
        misOrderNo: row.misNo,
        realStartTime: row.realStartTime,
        realEndTime: row.realEndTime
      };
      // finalizeFormData.value.content = row.content
      // 使用从属性传入的listWorkPerson方法
      if (typeof listWorkPerson === 'function') {
        listWorkPerson({ misNo: row.misNo }).then(response => {
          debugger
          const updatedData = {
            ...finalizeFormData.value,
            repairOrderPersonList: response.rows
          };
          if (response.rows) {
            debugger
            // 查找 isLeader 等于 1 的负责人（优先获取第一个符合条件的，贴合常规单负责人场景）
            const leaderPerson = response.rows.find(person => person.isLeader === 1);
            // 给 teamLeaderName 赋值
            updatedData.teamLeaderName = leaderPerson?.nickName || '';
            const nickNames = response.rows
                .filter(person => person.isLeader != 1)
                .map(person => person.nickName)
                .join(',');
            updatedData.workGroupMemberName = nickNames
          }
          finalizeFormData.value = updatedData;
        })
      }
      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;
      resetTimeOutOrder();
      getList();
    } catch (error) {
      proxy.$modal.msgError("操作失败: " + error.message);
    }
  });
}

const rightChecks = ref([])
function rightCheckHandler(val) {
  rightChecks.value = exportFieldsSelected.value
    .filter(item => val.includes(item))
  console.log(rightChecks.value, "rightCheckHandler")
}

function upDown(direction) {
   // 找出最小和最大索引
  const indices = rightChecks.value
    .map(i => exportFieldsSelected.value.indexOf(i))
    .filter(i => i !== -1)
  const minIndex = Math.min(...indices)
  const maxIndex = Math.max(...indices)
  // 边界检查
  if (direction === 'up' && minIndex === 0) {
    console.log('已到顶部')
    return
  }
  if (direction === 'down' && maxIndex === exportFieldsSelected.value.length - 1) {
    console.log('已到底部')
    return
  }
  if (direction === 'up') {
    rightChecks.value.map(i => {
      const index = exportFieldsSelected.value.findIndex(t => t == i)
      exportFieldsSelected.value.splice(index, 1);
      exportFieldsSelected.value.splice(index - 1, 0, i);
    })
  } else {
    rightChecks.value.slice().reverse().forEach(i => {
      const index = exportFieldsSelected.value.findIndex(t => t == i)
      if (index < exportFieldsSelected.value.length - 1) {
        exportFieldsSelected.value.splice(index, 1)
        exportFieldsSelected.value.splice(index + 1, 0, i)
      }
    })
  }
}

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

const formattedWorkArea = computed(() =>{
  if (!viewForm.value?.workArea) return '-'

  const values = viewForm.value.workArea.split(',').filter(v => v.trim())
  const dictList = unref(gxt_work_area) // 关键：解包 ref

  if (!Array.isArray(dictList)) {
    return viewForm.value.workArea
  }

  const dictMap = new Map(dictList.map(item => [item.value, item.label]))
  const labels = values.map(v => dictMap.get(v) || v)
  return labels.join('，') || '-'
})

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

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

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

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

//自动编码生成
function handleAutoGenChange(){
  genPostCode('REPAIR_ORDER_CODE', form.value).then(response =>{
    form.value.workOrderProjectNo = response;
  });
}

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

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