<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" 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="inspectionType" label-position="top">-->
<!--        <el-select v-model="queryParams.inspectionType" placeholder="请选择工单类型" clearable>-->
<!--          <el-option-->
<!--              v-for="dict in gxt_inspection_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="gxtCenter" label-position="top">-->
<!--        <el-input-->
<!--            v-model="queryParams.gxtCenter"-->
<!--            placeholder="请输入维保中心"-->
<!--            clearable-->
<!--            @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="场站" prop="pcsStationName" label-position="top">
        <el-select
            v-model="queryParams.pcsStationName"
            placeholder="请选择场站"
            clearable
            :disabled="!queryParams.gxtCenter"
        >
          <el-option
              v-for="item in stationOptions"
              :key="item.deptId"
              :label="item.deptName"
              :value="item.deptName">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="工单状态" prop="workOrderStatus" label-position="top">
        <el-select v-model="queryParams.workOrderStatus" placeholder="请选择工单状态" clearable>
          <el-option
              v-for="dict in gxt_work_order_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label-position="top">
          <div class="item-search">&nbsp;</div>
          <div class="item-search">
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          </div>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['worklog:gxt:maintenance:order:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['worklog:gxt:maintenance:order:remove']"
        >删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['gxt:maintenance:order:add']"
        >新建工单</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleBackFilling"
            v-hasPermi="['gxt:maintenance:order:add']"
        >补录工单</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="info"-->
<!--          icon="Upload"-->
<!--          @click="handleImport('order')"-->
<!--          v-hasPermi="['gxt:maintenance:order:import']"-->
<!--        >工单导入</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--            type="info"-->
<!--            icon="Upload"-->
<!--            @click="handleImport('person')"-->
<!--            v-hasPermi="['gxt:maintenance:order:import']"-->
<!--        >工单人员导入</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="Download"
          @click="handleExport"
          v-hasPermi="['gxt:maintenance:order:export']"
        >导出</el-button>
      </el-col>
      <!-- <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar> -->
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange" :key="forceKey">
      <el-table-column label="工单编码" align="center" prop="workOrderProjectNo" min-width="150" fixed>
        <template #default="scope">
          <el-button link type="primary" @click="handleDetail(scope.row)">
            {{ scope.row.workOrderProjectNo }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="风机编号" align="center" prop="pcsDeviceName" min-width="120" :show-overflow-tooltip="true">
        <template #default="scope">
          {{ scope.row.pcsDeviceName || '-' }}
        </template>
      </el-table-column>
<!--      <el-table-column label="维保类型" align="center" prop="inspectionType" min-width="100">-->
<!--        <template #default="scope">-->
<!--          <dict-tag v-if="scope.row.inspectionType" :options="gxt_inspection_type" :value="scope.row.inspectionType"/>-->
<!--          <span v-else>-</span>-->
<!--        </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="workOrderStatus" min-width="100">
        <template #default="scope">
          {{ scope.row.orderEntryType == '1' ? '新建工单' : '补录工单' }}
        </template>
      </el-table-column>
      <el-table-column label="维保中心" align="center" prop="gxtCenter" min-width="140" :show-overflow-tooltip="true">
        <template #default="scope">
          {{ scope.row.gxtCenter || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="场站" align="center" prop="pcsStationName" min-width="140" :show-overflow-tooltip="true">
        <template #default="scope">
          {{ scope.row.pcsStationName || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="品牌" align="center" prop="brand" min-width="140" :show-overflow-tooltip="true">
        <template  #default="scope">
          {{ scope.row.brand || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="机型" align="center" prop="model" min-width="140" :show-overflow-tooltip="true">
        <template #default="scope">
          {{ scope.row.model || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="MIS工单编码" align="center" prop="misNo" min-width="150">
        <template #default="scope">
          {{ scope.row.infoEntry == '1' ? scope.row.misNo || '-' : '-' }}
        </template>
      </el-table-column>
      <el-table-column label="工作票编号" align="center" prop="workPermitNum" min-width="150">
        <template #default="scope">
          {{ scope.row.workPermitNum || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="接单人" align="center" prop="acceptUserName">
        <template #default="scope">
          {{ scope.row.acceptUserName || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="接单时间" align="center" prop="acceptTime" width="100">
        <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="team_leader_name" width="100">
        <template #default="scope">
          {{ scope.row.teamLeaderName || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="realStartTime" min-width="140">
        <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" min-width="140">
        <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" min-width="200" class-name="small-padding fixed-width" fixed="right" >
        <template #default="scope">
<!--          <el-button-->
<!--              v-if="scope.row.workOrderStatus === 'draft'"-->
<!--              type="primary"-->
<!--              link-->
<!--              @click="handleUpdate(scope.row)"-->
<!--              v-hasPermi="['gxt:maintenance:order:edit']"-->
<!--          ><i class="fa fa-edit"></i>编辑</el-button>-->
          <el-button
              v-if="scope.row.workOrderStatus === 'to_issue'"
              type="primary"
              link
              @click="handleUpdate(scope.row)"
              v-hasPermi="['gxt:maintenance:order:edit']"
          ><i class="fa fa-user-plus"></i>下发</el-button>
          <!-- 已派单状态：只显示确认按钮 -->
          <el-button link type="primary" @click="handleAccept(scope.row)" v-if="scope.row.workOrderStatus === 'assigned'" v-hasPermi="['gxt:maintenance:order:accept']">
            <i class="fa fa-check"></i>接单
          </el-button>

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

          <!-- 已挂起状态：显示恢复按钮 -->
          <el-button link type="primary" @click="handleResume(scope.row)" v-if="(scope.row.workOrderStatus === 'suspended') && (scope.row.teamLeaderId == userStore.id || userStore.roles.includes('admin'))" v-hasPermi="['gxt:maintenance:order:resume']">
            <i class="fa fa-play"></i>恢复
          </el-button>

          <!-- 自动挂起状态：显示恢复按钮 -->
          <el-button link type="primary" @click="handleResume(scope.row)" v-if="(scope.row.workOrderStatus === 'auto_suspend')" v-hasPermi="['gxt:maintenance:order: autoResume']">
            <i class="fa fa-play"></i>恢复
          </el-button>

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

          <!-- 待结单状态：显示结单按钮 -->
          <el-button link type="success" @click="handleFinish(scope.row)" v-if="(scope.row.workOrderStatus === 'processing' || scope.row.workOrderStatus === 'to_finish') && scope.row.orderEntryType == '1'" v-hasPermi="['gxt:maintenance:order:complete']">
            <i class="fa fa-check"></i>结单
          </el-button>

          <!-- 补录结单-->
          <el-button link type="success" @click="handleBackfillingFinish(scope.row)" v-if="(scope.row.workOrderStatus === 'processing' || scope.row.workOrderStatus === 'to_finish') && scope.row.orderEntryType == '2'" v-hasPermi="['gxt:maintenance:order:complete']">
            <i class="fa fa-check"></i>结单
          </el-button>

          <el-button link type="danger" @click="handleShutdown(scope.row)"
                     v-if="scope.row.pauseTime == null && scope.row.workOrderStatus != 'to_issue' && scope.row.workOrderStatus != 'auto_suspend' && scope.row.workOrderStatus != 'completed' && scope.row.workOrderStatus != 'archived' && scope.row.workOrderStatus != 'invalid'"
                     v-hasPermi="['gxt:maintenance:order:shutdown']">
            <i class="fa fa-stop"></i>停机
          </el-button>

<!--          &lt;!&ndash; 已完成状态：显示评分按钮 &ndash;&gt;-->
<!--          <el-button link type="warning" @click="handleRate(scope.row)" v-if="scope.row.workOrderStatus === 'completed' && scope.row.score === null" v-hasPermi="['gxt:maintenance:order:rating']">-->
<!--            <i class="fa fa-star"></i>评分-->
<!--          </el-button>-->

          <!-- 已完成状态：显示复运按钮 -->
          <el-button link type="success" @click="handleRestart(scope.row)"
                     v-if="scope.row.restartTime == null && scope.row.workOrderStatus != 'to_issue' && scope.row.workOrderStatus != 'auto_suspend'"
                     v-hasPermi="['gxt:maintenance:order:restart']">
            <i class="fa fa-refresh"></i>复运
          </el-button>

          <el-button
              v-if="scope.row.workOrderStatus !== 'invalid'"
              type="danger"
              link
              @click="handleInvalidate(scope.row)"
              v-hasPermi="['gxt:maintenance:order:invalidate']"
          ><i class="fa fa-ban"></i>作废</el-button>

          <!-- 查看按钮对所有状态都显示 -->
          <el-button link type="info" @click="handleDetail(scope.row)" v-hasPermi="['gxt:maintenance:order: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:maintenance:order:remove']"
          ><i class="fa fa-trash"></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="title" v-model="open" width="800px" append-to-body>
      <div style="max-height: 500px; overflow-y: auto; padding-right: 10px;">
        <el-form ref="orderRef" :model="form" :rules="rules" label-width="120px" label-position="top">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="工单编码" prop="workOrderProjectNo">
                <el-input v-model="form.workOrderProjectNo" placeholder="自动生成" maxlength="50" show-word-limit v-chinese-limit readonly/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="风机编号" prop="pcsDeviceName">
                <el-input v-model="form.pcsDeviceName" readonly>
                  <template #append>
                    <el-button @click="handleSelectEquipment" icon="Search"></el-button>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="维保中心" prop="gxtCenter">
                <el-input v-model="form.gxtCenter" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="场站" prop="pcsStationName">
                <el-input v-model="form.pcsStationName" readonly />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="品牌" prop="brand">
                <el-input v-model="form.brand" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="机型" prop="model">
                <el-input v-model="form.model" readonly />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="维保类型" prop="inspectionType">
                <el-select v-model="form.inspectionType" multiple placeholder="请选择维保类型" clearable>
                  <el-option
                      v-for="dict in gxt_inspection_type"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
<!--          <el-row :gutter="20">-->
<!--            <el-col :span="12">-->
<!--              <el-form-item label="信息录入" prop="infoEntry">-->
<!--                <el-radio-group v-model="form.infoEntry" @change="handleInfoEntryChange">-->
<!--                  <el-radio-->
<!--                      v-for="dict in gxt_info_entry"-->
<!--                      :key="dict.value"-->
<!--                      :label="dict.value"-->
<!--                  >-->
<!--                    {{ dict.label }}-->
<!--                  </el-radio>-->
<!--                </el-radio-group>-->
<!--              </el-form-item>-->
<!--            </el-col>-->
<!--            <el-col :span="12" v-if="form.infoEntry == '1'">-->
<!--              <el-form-item label="MIS工单编码" prop="misNo">-->
<!--                <el-input v-model="form.misNo"-->
<!--                          placeholder="请输入MIS工单编码或点击搜索选择"-->
<!--                          clearable-->
<!--                          @focus="handleMisNoInputFocus"-->
<!--                          @blur="handleMisNoInputBlur"-->
<!--                          @input="handleMisNoInput"-->
<!--                          @clear="handleMisNoClear"-->
<!--                >-->
<!--                  <template #append>-->
<!--                    <el-button @click="handleSelectMisInfo" icon="Search"></el-button>-->
<!--                  </template>-->
<!--                </el-input>-->
<!--                &lt;!&ndash; 快速检索下拉框 &ndash;&gt;-->
<!--                <div class="quick-select-dropdown" v-show="showMisNoQuickSelect && quickMisNoList.length > 0">-->
<!--                  <div-->
<!--                      v-for="item in quickMisNoList"-->
<!--                      :key="item.misNo"-->
<!--                      class="quick-select-item"-->
<!--                      @click="handleMisNoQuickSelect(item)">-->
<!--                    <span class="mis-no">{{ item.misNo }}</span>-->
<!--                    &lt;!&ndash;                    <span class="mis-info">&ndash;&gt;-->
<!--                    &lt;!&ndash;                    <span class="device">{{ item.pcsDeviceName }}</span>&ndash;&gt;-->
<!--                    &lt;!&ndash;                    <span class="station">{{ item.pcsStationName }}</span>&ndash;&gt;-->
<!--                    &lt;!&ndash;                    </span>&ndash;&gt;-->
<!--                  </div>-->
<!--                </div>-->
<!--                <div class="quick-select-dropdown no-data" v-show="showMisNoQuickSelect && quickMisNoList.length === 0 && form.misNo">-->
<!--                  <div>未找到匹配的MIS工单</div>-->
<!--                </div>-->
<!--              </el-form-item>-->
<!--            </el-col>-->
<!--            <el-col :span="12" v-if="form.infoEntry == 2">-->
<!--              <el-form-item label="工作票编号" prop="workPermitNum">-->
<!--                <el-input v-model="workPermitNumProxy"  maxlength="20" show-word-limit />-->
<!--              </el-form-item>-->
<!--            </el-col>-->
<!--          </el-row>-->

          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="维保内容" prop="content">
                <el-input v-model="form.content" type="textarea" :rows="3" maxlength="500" show-word-limit />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
<!--          <el-button type="primary" @click="submitAccept">确 认</el-button>-->
          <el-button @click="open = false">取 消</el-button>
          <el-button type="primary" @click="submitForm('to_issue')" v-if="optType == 'add'">保 存</el-button>
          <el-button type="primary" @click="submitForm('assigned')" v-if="optType == 'add'">保存并下发</el-button>
          <el-button type="primary" @click="submitForm('assigned')" v-if="optType == 'edit'">确认下发</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 补录对话框 -->
    <el-dialog :title="title" v-model="backfillDialogVisible" width="800px" append-to-body>
      <div style="max-height: 500px; overflow-y: auto; padding-right: 10px;">
        <el-form ref="orderRef" :model="form" :rules="rules" label-width="120px" label-position="top">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="工单编码" prop="workOrderProjectNo">
                <el-input v-model="form.workOrderProjectNo" placeholder="自动生成" maxlength="50" show-word-limit v-chinese-limit readonly/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="风机编号" prop="pcsDeviceName">
                <el-input v-model="form.pcsDeviceName" readonly>
                  <template #append>
                    <el-button @click="handleSelectEquipment" icon="Search"></el-button>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="维保中心" prop="gxtCenter">
                <el-input v-model="form.gxtCenter" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="场站" prop="pcsStationName">
                <el-input v-model="form.pcsStationName" readonly />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="品牌" prop="brand">
                <el-input v-model="form.brand" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="机型" prop="model">
                <el-input v-model="form.model" readonly />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="信息录入" prop="infoEntry">
                <el-radio-group v-model="form.infoEntry" @change="handleInfoEntryChange">
                  <el-radio
                      v-for="dict in gxt_info_entry"
                      :key="dict.value"
                      :label="dict.value"
                  >
                    {{ dict.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="form.infoEntry == '1'">
              <el-form-item label="MIS工单编码" prop="misNo">
                <el-input v-model="form.misNo"
                          placeholder="请输入MIS工单编码或点击搜索选择"
                          clearable
                          @focus="handleMisNoInputFocus"
                          @blur="handleMisNoInputBlur"
                          @input="handleMisNoInput"
                          @clear="handleMisNoClear"
                >
                  <template #append>
                    <el-button @click="handleSelectMisInfo" icon="Search"></el-button>
                  </template>
                </el-input>
                <!-- 快速检索下拉框 -->
                <div class="quick-select-dropdown" v-show="showMisNoQuickSelect && quickMisNoList.length > 0">
                  <div
                      v-for="item in quickMisNoList"
                      :key="item.misNo"
                      class="quick-select-item"
                      @click="handleMisNoQuickSelect(item)">
                    <span class="mis-no">{{ item.misNo }}</span>
                    <!--                    <span class="mis-info">-->
                    <!--                    <span class="device">{{ item.pcsDeviceName }}</span>-->
                    <!--                    <span class="station">{{ item.pcsStationName }}</span>-->
                    <!--                    </span>-->
                  </div>
                </div>
                <div class="quick-select-dropdown no-data" v-show="showMisNoQuickSelect && quickMisNoList.length === 0 && form.misNo">
                  <div>未找到匹配的MIS工单</div>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工作票编号" prop="workPermitNum">
                <el-input v-model="workPermitNumProxy"  maxlength="20" show-word-limit />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="维保内容" prop="content" :required="form.infoEntry == '2'">
                <el-input v-model="form.content" type="textarea" :rows="3" :readonly="form.infoEntry == '1'" maxlength="500" show-word-limit />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <!--          <el-button type="primary" @click="submitAccept">确 认</el-button>-->
          <el-button @click="backfillDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm('to_issue')" v-if="optType == 'add'">保 存</el-button>
          <el-button type="primary" @click="submitForm('assigned')" v-if="optType == 'add'">保存并下发</el-button>
          <el-button type="primary" @click="submitForm('assigned')" v-if="optType == 'edit'">确认下发</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 接单对话框 -->
    <el-dialog :title="'接单'" v-model="acceptDialogVisible" width="800px" append-to-body>
<!--      <div style="max-height: 500px; overflow-y: auto; padding-right: 10px;">-->
        <el-form ref="acceptRef" :model="acceptForm" :rules="acceptRules" label-width="120px" label-position="top">
          <el-row :gutter="20">
            <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-row>
          <el-row :gutter="20">
            <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-row>
          <el-row :gutter="20">
            <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.model" disabled />
              </el-form-item>
            </el-col>
          </el-row>
<!--          <el-row :gutter="20">-->
<!--            <el-col :span="12" v-if="acceptForm.infoEntry == '1'">-->
<!--              <el-form-item label="MIS工单编码">-->
<!--                <el-input v-model="acceptForm.misNo" disabled />-->
<!--              </el-form-item>-->
<!--            </el-col>-->
<!--            <el-col :span="12" v-if="acceptForm.infoEntry == '2'">-->
<!--              <el-form-item label="工作票编号">-->
<!--                <el-input v-model="acceptForm.workPermitNum" disabled />-->
<!--              </el-form-item>-->
<!--            </el-col>-->
<!--          </el-row>-->
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="维保内容" prop="content">
                <el-input v-model="acceptForm.content" type="textarea" :rows="3" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <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>
<!--      </div>-->
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="acceptDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitAccept">确认接单</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 开始处理对话框 -->
    <el-dialog title="开始处理工单" v-model="startDialogVisible" width="800px" append-to-body>
      <div class="space-y-4">
<!--        <div class="bg-blue-50 border-l-4 border-blue-400 p-4">-->
        <p class="text-sm text-blue-700">
          <el-alert type="primary" :closable="false">
            <template #default>
              <i class="fa fa-info-circle mr-2"></i> 确认开始处理该工单？开始后工单状态将变为"处理中"。
            </template>
          </el-alert>
        </p>
<!--        </div>-->
        <el-row :gutter="20">
          <el-col :span="12">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">工单编码</label>
              <el-input v-model="startForm.orderCode" disabled />
            </div>
          </el-col>
          <el-col :span="12">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">风机编号</label>
              <el-input v-model="startForm.pcsDeviceName" disabled />
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">维保内容</label>
              <el-input v-model="startForm.content" type="textarea" placeholder="维保内容" :rows="3" disabled />
            </div>
          </el-col>
        </el-row>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="startDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitStart">确认开始</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 继续处理对话框 -->
    <el-dialog title="恢复工单" v-model="resumeDialogVisible" width="800px" append-to-body>
      <div class="text-center py-6">
        <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-green-100 text-green-600 mb-4">
          <i class="fa fa-play text-2xl"></i>
        </div>
        <h4 class="text-lg font-medium mb-2">确定要恢复工单吗？</h4>
        <p class="text-gray-500 mb-4">工单编码：{{ resumeForm.orderCode }}</p>
        <p class="text-gray-500 text-sm">恢复后，工单状态将变为"待结单"</p>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="resumeDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitResume">确认恢复</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 结单对话框组件 -->
    <FinalizeDialog
      v-model="finishDialogVisible"
      :data="finishForm"
      :work-order-status-options="gxt_work_order_status"
      :info-entry-options="gxt_info_entry"
      :list-gxt-order="listGxtOrder"
      :list-work-person="listWorkPerson"
      :list-mis-info="listMisInfo"
      :list-user-data="listUserData"
      :on-submit="submitFinishFromParent"
      :info-entry-disabled = "infoEntryDisabled"
      @success="handleFinishSuccess"
      @select-mis-info="handleSelectMisInfo2"
    >
      <template #mis-info-select>
        <MisInfoSelectSingle :key="commonKey" v-model="misInfoSelectVisible2" @onSelected="onMisInfoSelected2" :pcsStationName="finishForm.pcsStationName" :pcsDeviceName="finishForm.pcsDeviceName" :workOrderStatus="结束" ></MisInfoSelectSingle>
      </template>
    </FinalizeDialog>

    <!-- 补录结单对话框组件 -->
    <BackfillFinalizeDialog
        v-model="backfillFinishDialogVisible"
        :data="finishForm"
        :work-order-status-options="gxt_work_order_status"
        :list-user-data="listUserData"
        :on-submit="submitFinishFromParent"
        @success="handleFinishSuccess"
    >
<!--      <template #mis-info-select>-->
<!--        <MisInfoSelectSingle :key="commonKey" v-model="misInfoSelectVisible" @onSelected="onMisInfoSelected" :pcsStationName="finishForm.pcsStationName" :pcsDeviceName="finishForm.pcsDeviceName"></MisInfoSelectSingle>-->
<!--      </template>-->
    </BackfillFinalizeDialog>

    <!-- 维保挂起对话框 -->
    <SuspendDialog
        v-model="suspendDialogVisible"
        :data="suspendForm"
        :suspend-reason-options="gxt_order_suspend_reason"
        :on-submit="submitSuspendFromParent"
        @success="handleSuspendSuccess"
    />
    <!-- 复运对话框 -->
    <el-dialog title="复运" v-model="restartDialogVisible" width="800px" append-to-body>
      <div class="space-y-4">
        <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>

        <el-form ref="restartRef" :model="restartForm" :rules="restartRules" label-width="120px" label-position="top">
          <!-- 工单信息 -->
          <h4 class="text-sm font-medium text-gray-800 mb-3"></h4>
          <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="工单状态" prop="workOrderStatus">-->
<!--                <el-select v-model="restartForm.workOrderStatus" 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-row>-->
<!--          <el-row>-->
            <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-row>-->
<!--          <el-row>-->
            <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-row>-->
<!--          <el-row>-->
<!--            <el-col :span="12">-->
<!--              <el-form-item label="机型">-->
<!--                <el-input v-model="restartForm.model" disabled />-->
<!--              </el-form-item>-->
<!--            </el-col>-->
            <el-col :span="12">
              <el-form-item label="开始时间"><el-input v-model="restartForm.realStartTime" 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.misNo" 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"
                    placeholder="请选择恢复运行时间"
                    format="YYYY-MM-DD HH:mm"
                    value-format="YYYY-MM-DD HH:mm"
                    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"
                    controls-position="right"
                    style="width: 100%"
                    class="input-number-left"
                    :min="0"
                    placeholder="请输入损失电量"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="restartDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitRestart">确认复运</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 评分对话框 -->
    <el-dialog title="评价维保工单" v-model="rateDialogVisible" width="900px" append-to-body>
      <div class="space-y-4">
        <el-alert type="info" :closable="false" style="border-color: #6366f1; background-color: #eef2ff; color: #4f46e5; height: 35px;">
          <template #default>
            <i class="fa fa-star mr-2" style="color: #4f46e5;"> 请对该维保工单进行评分和点评，评分最高为10分。</i>
          </template>
        </el-alert>

        <!-- 工单信息 -->
        <h4 class="text-sm font-medium text-gray-800 mb-3">工单信息</h4>
        <el-form ref="rateRef" :model="rateForm" :rules="rateRules" label-width="120px" label-position="top">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="工单编码">
                <el-input v-model="rateForm.workOrderProjectNo" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工单状态" prop="workOrderStatus">
                <el-select v-model="rateForm.workOrderStatus" 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-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="风机编号">
                <el-input v-model="rateForm.pcsDeviceName" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="维保中心">
                <el-input v-model="rateForm.gxtCenter" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="场站">
                <el-input v-model="finishForm.pcsStationName" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="品牌">
                <el-input v-model="finishForm.brand" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="机型">
                <el-input v-model="finishForm.model" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="MIS工单编码">
                <el-input v-model="finishForm.misNo" disabled />
              </el-form-item>
            </el-col>
          </el-row>
        <!-- 处理信息 -->
<!--        <h4 class="text-sm font-medium text-gray-800 mb-3">处理信息</h4>-->
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="工作负责人">
                <el-input v-model="rateForm.teamLeaderName" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工作班成员">
                <el-input v-model="rateForm.workGroupMemberName" disabled />
              </el-form-item>
            </el-col>
          </el-row>
        <!-- 维保内容 -->
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="维保内容">
                <el-input v-model="rateForm.content" type="textarea" :rows="3" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="附件">
                <preview :limit="8" v-model="rateForm.attachmentUrls" :filesize="5" disabled></preview>
              </el-form-item>
            </el-col>
          </el-row>
        <!-- 评分表单 -->
          <el-form-item label="评分" prop="score" required>
            <div class="flex items-center">
              <el-rate v-model="rateForm.score" allow-half show-score text-color="#ff9900" />
              <span class="ml-2 text-gray-500">/ 10分</span>
            </div>
          </el-form-item>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="评分" prop="score">
                <el-input-number
                    v-model="rateForm.score"
                    :min="1"
                    :max="10"
                    controls-position="right"
                    style="width: 100%"
                    class="input-number-left"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="点评" prop="reviewContent">
                <el-input
                  v-model="rateForm.reviewContent"
                  type="textarea"
                  placeholder="请输入点评内容，最多100字"
                  maxlength="100"
                  :rows="3"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="rateDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitRate">提交评分</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 审批挂起对话框 -->
    <!-- 审批对话框组件 -->
    <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"
    />

    <!-- 停机对话框组件 -->
    <ShutdownDialog
        v-model="shutdownDialogVisible"
        :data="shutdownForm"
        :on-submit="submitShutdownFormParent"
        @success="handleShutdownSuccess"
    />

    <!-- 流转记录对话框 -->
    <el-dialog title="工单流转记录" v-model="flowDialogVisible" width="900px" append-to-body>
      <el-timeline>
        <el-timeline-item
          v-for="flow in flowList"
          :key="flow.id"
          :timestamp="parseTime(flow.actionTime, '{y}-{m}-{d} {h}:{i}')"
          placement="top"
        >
          <el-card>
            <h4>{{ getActionTypeName(flow.actionType) }}</h4>
            <p>操作人：{{ flow.operatorName }}</p>
            <p>状态变更：{{ getStatusName(flow.fromStatus) }} → {{ getStatusName(flow.toStatus) }}</p>
            <p v-if="flow.actionRemark">备注：{{ flow.actionRemark }}</p>
          </el-card>
        </el-timeline-item>
      </el-timeline>
    </el-dialog>

    <!-- 查看工单详情对话框 -->
    <ViewDialog
        v-model="detailDialogVisible"
        :data="detailData"
        :work-order-status-options="gxt_work_order_status"
        :repair-order-flow-action-type-options="gxt_repair_order_flow_action_type"
        :inspection-type-options="gxt_inspection_type"
        :finalize-method-options="gxt_finalize_method"
    />

    <!-- 作废工单对话框 -->
    <el-dialog title="作废工单" v-model="invalidateDialogVisible" width="800px" append-to-body>
      <el-form ref="invalidateRef" :model="invalidateForm" :rules="invalidateRules" label-width="120px" label-position="top">
        <el-alert type="warning" :closable="false" style="margin-bottom: 20px;">
          <template #default>
            <i class="fa fa-exclamation-circle mr-2"></i>
            确定要作废该工单吗？作废后工单状态将变为"已作废"且不可恢复。
          </template>
        </el-alert>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="工单编码">
              <el-input v-model="invalidateForm.workOrderProjectNo" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="作废原因" prop="invalidReason">
              <el-input
                  v-model="invalidateForm.invalidReason"
                  type="textarea"
                  :rows="4"
                  placeholder="请输入作废原因"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="invalidateDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitInvalidate">确认作废</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>

    <!-- 工单人员导入对话框 -->
    <el-dialog :title="personUpload.title" v-model="personUpload.open" width="400px" append-to-body>
      <el-upload ref="personUploadRef" :limit="1" accept=".xlsx, .xls" :headers="personUpload.headers" :action="personUpload.url" :disabled="personUpload.isUploading" :on-progress="handlePersonFileUploadProgress" :on-success="handlePersonFileSuccess" :on-change="handlePersonFileChange" :on-remove="handlePersonFileRemove" :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">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importPersonTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitPersonFileForm">确 定</el-button>
          <el-button @click="personUpload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- MIS选择组件 -->
    <MisInfoSelectSingle :key="commonKey" v-model="misInfoSelectVisible" @onSelected="onMisInfoSelected" :pcsDeviceName="form.pcsDeviceName"></MisInfoSelectSingle>
    <!-- 设备选择组件 -->
    <equipment-select-single v-model="equipmentSelectVisible" @onSelected="onEquipmentSelected"></equipment-select-single>
    <!-- 字段选择对话框 -->
    <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>
  </div>
</template>

<script setup name="GxtOrder">
import preview from '@/components/FileUpload/preview.vue'
import {
  listGxtOrder,
  getGxtOrder,
  delGxtOrder,
  addGxtOrder,
  updateGxtOrder,
  assignToTeamLeader,
  acceptByTeamLeader,
  assignToWorkGroupMember,
  acceptByWorkGroupMember,
  suspendWorkOrder,
  restartWorkOrder,
  completeWorkOrder,
  getWorkOrderFlow,
  acceptOrder,
  startWorkOrder,
  pauseWorkOrder,
  resumeWorkOrder,
  approveWorkOrder,
  uploadAttachments,
  importGxtOrder,
  importGxtWorkOrderPerson,
  importGxtWorkOrderPersonFromExcel,
  // importTemplate
  invalidateGxtOrder,
  getExportFields, shutdownOrder
} from "@/api/gxt/gxtOrder"
import {listUserData, listUserNoPermi, listLeader} from "@/api/system/user"
import {getToken} from "@/utils/auth.js";
import {getRepairOrder, listRepairOrder, startRepairOrder} from "@/api/gxt/repairOrder.js";
import FinalizeDialog from '@/components/gxtOrder/finalize.vue'
import {listEquipment, listMaintenanceCenters, listStationsByMaintenanceCenter} from "@/api/gxt/equipment.js";import MisInfoSelectSingle from "@/components/misInfoSelect/single.vue";
import {genPostCode} from "@/api/system/autocode/rule.js";
import {listAutoMisInfo, listMisInfo, listWorkPerson} from "@/api/gxt/misInfo.js";
import {ElMessageBox} from "element-plus";
import EquipmentSelectSingle from "@/components/equipmentSelect/single.vue";
import useUserStore from '@/store/modules/user'
import SuspendDialog from "@/components/gxtOrder/suspend.vue";
import ViewDialog from "@/components/gxtOrder/view.vue";
import ApproveDialog from "@/components/gxtOrder/approve.vue";
import ShutdownDialog from "@/components/gxtOrder/shutdown.vue";
import BackfillFinalizeDialog from '@/components/gxtOrder/backfillFinalize.vue'
import { useRoute } from 'vue-router';
import { watch } from 'vue';
const route = useRoute(); // 获取当前路由信息

// 初始化禁用状态为 false（单选框默认可用）
const infoEntryDisabled = ref(false);
// 工作负责人快速检索相关响应式数据
const showTeamLeaderQuickSelect = ref(false)
const quickTeamLeaderList = ref([])
const teamLeaderLoading = ref(false)
const teamLeaderSearchTimer = ref(null)
const allUserList = ref([]) // 存储所有设备数据用于快速检索
const lastLoadedCenterId = ref(null) // Track last loaded maintenance center ID
const userStore = useUserStore();
const forceKey = ref(0)

/** 过滤快速检索用户列表 */
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)
  }

  // 设置新的定时器，防抖处理（300ms）
  // teamLeaderSearchTimer.value = setTimeout(() => {
    // searchTeamLeaderList(searchText)
  filterQuickUserList(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 && lastLoadedCenterId.value === acceptForm.value.gxtCenterId) {
    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)
}

/** 搜索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: form.value.pcsDeviceName,
      // 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工单相关的字段
  form.value.misNo = null
  form.value.content = null
  form.value.workPermitNum = null
  // form.value.pcsDeviceName = null
  // form.value.pcsStationName = null
  // form.value.pcsDeviceId = null
  // form.value.gxtCenter = null
  // form.value.brand = null
  // form.value.model = null
  quickMisNoList.value = []
  showMisNoQuickSelect.value = false
}

const { proxy } = getCurrentInstance()
const {
  gxt_work_order_status,
  gxt_inspection_type,
  gxt_pause_reasons,
  gxt_repair_order_flow_action_type,
  gxt_order_suspend_reason,
  gxt_info_entry,
  gxt_finalize_method
} = proxy.useDict(
    "gxt_work_order_status",
    "gxt_inspection_type",
    "gxt_pause_reasons",
    "gxt_repair_order_flow_action_type",
    "gxt_order_suspend_reason",
    "gxt_info_entry",
    "gxt_finalize_method"
)
const orderList = ref([])
const open = 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 title = ref("")
const assignDialogVisible = ref(false)
const suspendDialogVisible = ref(false)
const pauseDialogVisible = ref(false)
const startDialogVisible = ref(false)
const resumeDialogVisible = ref(false)
const completeDialogVisible = ref(false)
const finishDialogVisible = ref(false)
const rateDialogVisible = ref(false)
const approveDialogVisible = ref(false)
const flowDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const acceptDialogVisible = ref(false)
const restartDialogVisible = ref(false)
const equipmentSelectVisible = ref(false)
const invalidateDialogVisible = ref(false)
const shutdownDialogVisible = ref(false)
const backfillDialogVisible = ref(false)
const backfillFinishDialogVisible = ref(false)
const userList = ref([])
const flowList = ref([])
const detailData = ref({})
// 维保中心和场站选项
const maintenanceCenterOptions = ref([])
const stationOptions = ref([])
// 在 data 部分添加
const fileUploadRef = ref(null)

const tableHeight = ref(window.innerHeight - 300)
const misInfoSelectVisible = ref(false)
const misInfoSelectVisible2 = ref(false)
let commonKey = 0
const optType = ref("")

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

const personUpload = reactive({
  // 是否显示弹出层（人员导入）
  open: false,
  // 弹出层标题（人员导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 选中的文件
  selectedFile: null,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/gxt/workOrderPerson/importData"
})

const data = reactive({
  form: {
    // pcsDeviceName: undefined,
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    workOrderProjectNo: undefined,
    workOrderStatus: undefined,
    gxtCenter: undefined,
    pcsStationName: undefined,
    orderSource: undefined
  },
  rules: {

    // workOrderProjectNo: [{ required: true, message: "工单编码不能为空", trigger: "blur" }],
    misNo: [{ required: true, message: "MIS编码不能为空", trigger: "change" }],
    pcsDeviceName: [{ required: true, message: "风机编号不能为空", trigger: "change" }],
    inspectionType: [{ required: true, message: "维保类型不能为空", trigger: "change" }],
    // workOrderStatus: [{ required: true, message: "工单状态不能为空", trigger: "change" }],
    // gxtCenter: [{ required: true, message: "维保中心不能为空", trigger: "blur" }],
    // pcsStationName: [{ required: true, message: "风电场不能为空", trigger: "blur" }],
    // workPermitNum: [
    //   { required: true, message: "工作票编号不能为空", trigger: "blur" }
    // ],
    workPermitNum: [
      { required: true, message: "工作票编号不能为空", trigger: "change" },
      {
        validator: (rule, value, callback) => {
          if (form.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) {
                listGxtOrder({pageNum: 1, pageSize: 10, workPermitNum: value}).then(response => {
                  const gxtOrders = response.rows
                  if (gxtOrders.length > 0) {
                    if (form.value.id == null) {
                      callback(new Error('工作票编号已存在！'))
                    } else {
                      if (gxtOrders[0].id != form.value.id) {
                        callback(new Error('工作票编号已存在！'))
                      } else {
                        callback()
                      }
                    }
                  } else {
                    callback()
                  }
                })
              } else {
                callback()
              }
            }
          } else {
            callback()
          }
        },
        trigger: 'blur'
      }
    ],    // 动态控制 content 是否必填
    content: [
      { required: true, message: "维保内容不能为空", trigger: "change" },
      // {
      //   validator: (rule, value, callback) => {
      //     // 当 infoEntry == 2 时才校验必填
      //     if (form.value.infoEntry == '2') {
      //       if (!value || value.trim() === '') {
      //         callback(new Error('维保内容不能为空'));
      //       } else {
      //         callback();
      //       }
      //     } else {
      //       // 不是 infoEntry=2 时，不校验，直接通过
      //       callback();
      //     }
      //   },
      //   trigger: 'blur'
      // }
    ]
  },
  assignForm: {
    assignType: 'teamLeader',
    teamLeaderId: undefined,
    teamLeaderName: undefined,
    workGroupMemberId: undefined,
    workGroupMemberName: undefined,
    orderId: undefined
  },
  assignRules: {
    teamLeaderId: [{ required: true, message: "请选择班组组长", trigger: "change" }],
    workGroupMemberId: [{ required: true, message: "请选择工作组成员", trigger: "change" }]
  },
  suspendForm: {
    orderId: undefined,
    orderCode: undefined,
    pcsDeviceName: undefined,
    content: undefined,
    suspendReason: undefined,
    remark: undefined
  },
  suspendRules: {
    suspendReason: [{ required: true, message: "请选择挂起原因", trigger: "change" }],
    remark: [{ required: true, message: "请输入详细说明", trigger: "blur" }]
  },
  pauseForm: {
    orderId: undefined,
    orderCode: undefined,
    pauseReason: undefined,
    remark: undefined
  },
  pauseRules: {
    pauseReason: [{ required: true, message: "请选择暂停原因", trigger: "change" }]
  },
  startForm: {
    orderId: undefined,
    orderCode: undefined,
    pcsDeviceName: undefined,
    content: undefined
  },
  resumeForm: {
    orderId: undefined,
    orderCode: undefined
  },
  completeForm: {
    orderId: undefined,
    orderCode: undefined
  },
  finishForm: {
    orderId: undefined,
    orderCode: undefined,
    workOrderProjectNo: undefined,
    pcsDeviceName: undefined,
    orderType: undefined,
    workOrderStatus: undefined,
    gxtCenter: undefined,
    pcsStationName: undefined,
    brand: undefined,
    model: undefined,
    acceptUserName: undefined,
    acceptTime: undefined,
    teamLeaderName: undefined,
    workGroupMemberName: undefined,
    content: undefined,
    issuerName: undefined,
    permitterName: undefined,
    stopTime: undefined,
    restoreTime: undefined,
    workOrderPersonList: []
  },
  rateForm: {
    orderId: undefined,
    orderCode: undefined,
    workOrderProjectNo: undefined,
    pcsDeviceName: undefined,
    orderType: undefined,
    workOrderStatus: undefined,
    acceptUserName: undefined,
    teamLeaderName: undefined,
    workGroupMemberName: undefined,
    content: undefined,
    score: undefined,
    reviewContent: undefined
  },
  approveForm: {
    orderId: undefined,
    workOrderProjectNo: undefined,
    pcsDeviceName: undefined,
    orderType: undefined,
    acceptUserName: undefined,
    acceptTime: undefined,
    gxtCenter: undefined,
    pcsStationName: undefined,
    brand: undefined,
    model: undefined,
    misNo: undefined,
    teamLeaderName: undefined,
    workGroupMemberName: undefined,
    suspendReason: undefined,
    workOrderStatus: 'suspended',
    rejectionReason: undefined
  },
  shutdownForm: {
  },
  rateRules: {
    score: [{ required: true, message: "请选择评分", trigger: "change" }],
    reviewContent: [{ required: false, message: "请输入点评", trigger: "blur" }]
  },
  approveRules: {
    workOrderStatus: [{ required: true, message: "请选择审批结果", trigger: "change" }],
    rejectionReason: [
      {
        required: true,
        message: "请输入驳回理由",
        trigger: "blur",
        validator: (rule, value, callback) => {
          if (data.approveForm.workOrderStatus === 'to_finish' && !value) {
            callback(new Error("驳回理由必填"))
          } else {
            callback()
          }
        }
      }
    ]
  },
  acceptForm: {
    orderId: undefined,
    orderCode: undefined,
    workOrderProjectNo: undefined,
    pcsDeviceName: undefined,
    orderType: undefined,
    gxtCenter: undefined,
    pcsStationName: undefined,
    brand: undefined,
    model: undefined,
    misNo: undefined,
    content: undefined,
    assignUserName: undefined,
    assignTime: undefined,
    planStartTime: undefined,
    teamLeaderId: undefined,
    teamLeaderName: undefined,
    memberIds: [],
    workOrderPersonList: []
  },
  acceptRules: {
    // inspectionType: [{ required: true, message: "请选择维保类型", trigger: "change" }],
    // content: [{ required: true, message: "请输入维保内容", trigger: "blur" }],
    // teamLeaderId: [{ required: true, message: "请选择工作负责人", trigger: "change" }],
    // memberIds: [{ required: true, message: "请至少选择一名工作班成员", trigger: "change" }]
  },
  finishRules: {
    realStartTime: [{ required: true, message: "请选择开始时间", trigger: "change" },
      {
        validator: (rule, value, callback) => {
          if (value && new Date(value) > new Date() && finishForm.value.infoEntry ==  '2') {
            callback(new Error('开始时间不能大于当前时间'));
          } else if(value && new Date(value) < new Date(finishForm.value.acceptTime) && finishForm.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() && finishForm.value.infoEntry ==  '2') {
            callback(new Error('结束时间不能大于当前时间'));
          } else if(value && new Date(value) < new Date(finishForm.value.realStartTime) && finishForm.value.infoEntry ==  '2') {
            callback(new Error('结束时间不能小于开始时间'));
          } else {
            callback();
          }
        },
        trigger: 'change'
      }
    ],
    workGroupMemberName: [
      { required: false, message: "请输入工作班成员", trigger: "blur" },
      {
        validator: async (rule, value, callback) => {
          // 如果值为空、关联MIS，直接通过验证
          if (!value || finishForm.value.infoEntry ==  '1') {
            return callback();
          }
          try {
            // 将输入的工作班成员姓名按逗号分割
            const names = value.split(',').map(name => name.trim());
            // 验证每个工作班成员是否存在于组织架构中
            for (const name of names) {
              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'
      }
    ],
    // teamLeaderId: [{ required: true, message: "请选择工作负责人", trigger: "change" }],
    // inspectionType: [{ required: true, message: "请选择维保类型", trigger: "change" }],
    // realContent: [{ required: true, message: "请输入实际维保内容", trigger: "change" }],
    // memberIds: [{ required: true, message: "请至少选择一名工作班成员", trigger: "change" }],
  },
  restartForm: {
    orderId: undefined,
    orderCode: undefined,
    workOrderProjectNo: undefined,
    pcsDeviceName: undefined,
    inspectionType: undefined,
    content: undefined,
    restartTime: undefined,
    lostPower: undefined,
    score: undefined  // 用于判断是否已评分
  },
  restartRules: {
    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'
      }
    ]
  },
  invalidateForm: {
    id: undefined,
    workOrderProjectNo: undefined,
    invalidReason: undefined
  },
  invalidateRules: {
    invalidReason: [{ required: true, message: "请输入作废原因", trigger: "blur" }]
  },
})

// 导出字段相关变量
const showExportFieldsDialog = ref(false)
const exportFieldsData = ref([])
const exportFieldsSelected = ref([])

const { queryParams, form, rules, assignForm, assignRules, suspendForm, suspendRules, pauseForm, pauseRules, startForm,
  resumeForm, completeForm, finishForm, rateForm, rateRules, approveForm, approveRules, acceptForm, acceptRules, finishRules, restartForm, restartRules, invalidateForm, invalidateRules, shutdownForm } = toRefs(data)

onMounted(() => {
  getList()
  getMaintenanceCenterAndStationList()
  // getGetMisDataConfig() // 获取配置参数
  getExportFieldsData() // 获取导出字段数据
  window.addEventListener('resize', handleResize)

})

// 监听路由变化（包括首次加载和后续跳转）
watch(
  () => route.path, // 监听路由路径变化（也可监听 route.params、route.query 等）
  (newPath, oldPath) => {
    getFromRoute(); // 执行的逻辑
  },
  { immediate: true } // 立即触发一次（首次加载时执行）
);

function getFromRoute () {
  // 检查是否从月度工分汇总页面跳转而来，如果有工单编号则自动筛选
  const fromRoute = sessionStorage.getItem('fromRoute');
  const workOrderNo = sessionStorage.getItem('workOrderProjectNo');
  if (fromRoute === '/workScore/monthScore' && workOrderNo) {
    // 更新查询参数
    queryParams.value.workOrderProjectNo = workOrderNo;
    listGxtOrder(queryParams.value).then(response => {
      if(response.rows && response.rows.length > 0) {
        handleDetail(response.rows[0]);
      }
    })
    // 清除sessionStorage中的临时数据
    sessionStorage.removeItem('fromRoute');
    sessionStorage.removeItem('workOrderProjectNo');
  }
}

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 getList() {
  loading.value = true
  listGxtOrder(queryParams.value).then(response => {
    orderList.value = response.rows
    total.value = response.total
    loading.value = false
    forceKey.value += 1
  })
}

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

/** 表单重置 */
function reset() {
  form.value = {
    id: undefined,
    workOrderProjectNo: undefined,
    workOrderStatus: 'draft',
    gxtCenter: undefined,
    pcsStationName: undefined,
    pcsDeviceName: undefined,
    brand: undefined,
    model: undefined,
    inspectionType: undefined,
    workPlanNo: undefined,
    planStartTime: undefined,
    planEndTime: undefined,
    orderSource: undefined,
    remark: undefined,
    content: undefined,
    planHour: undefined,
    faultCode: undefined,
    faultDesc: undefined,
    orderType: undefined,
    priorityType: undefined
  }
  proxy.resetForm("orderRef")
}

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

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

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

/** 新增按钮操作 */
function handleAdd() {
  reset()
  // form.value.infoEntry = "1"
  open.value = true
  title.value = "新建维保工单"
  optType.value = "add"
  commonKey++
}

/**
 *
 *
 * 补录按钮操作
 */
function handleBackFilling() {
  reset()
  form.value.infoEntry = "1"
  form.value.orderEntryType = "2"
  backfillDialogVisible.value = true
  title.value = "补录维保工单"
  optType.value = "add"
  commonKey++
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const id = row.id || ids.value
  getGxtOrder(id).then(response => {
    form.value = response.data
    // 关键：处理 inspectionType 逗号字符串 -> 数组，支持多选回填
    if (form.value.inspectionType) {
      // 1. 分割字符串为数组（去除首尾空格，避免空值）
      form.value.inspectionType = form.value.inspectionType
          .toString() // 确保是字符串类型，防止报错
          .trim() // 去除首尾空格
          .split(',') // 按逗号分割为数组
          .filter(item => item) // 过滤空字符串（避免分割后出现 [""] 无效值）
    } else {
      // 无数据时赋值为空数组，避免 v-model 绑定非数组类型
      form.value.inspectionType = []
    }
    if (form.value.orderEntryType == '2') {
      backfillDialogVisible.value = true
    } else {
      open.value = true
    }
    title.value = "下发"
    optType.value = "edit"
    commonKey++
  })
}

/** 提交按钮 */
function submitForm(status) {
  proxy.$refs["orderRef"].validate(valid => {
    if (valid) {
      form.value.workOrderStatus = status
      form.value.inspectionType = Array.isArray(form.value.inspectionType) ? form.value.inspectionType.join(',')
          : form.value.inspectionType || ''
      if (form.value.id != undefined) {
        updateGxtOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("下发成功")
          open.value = false
          backfillDialogVisible.value = false
          getList()
        })
      } else {
        addGxtOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("新建成功")
          open.value = false
          backfillDialogVisible.value = false
          getList()
        })
      }
    }
  })
}

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

/** 详情按钮操作 */
function handleDetail(row) {
  debugger
  getGxtOrder(row.id).then(response => {
    detailData.value = response.data
    // 从工单详情中获取流转记录
    flowList.value = response.data.workOrderFlowList || []
    debugger
    detailDialogVisible.value = true
  })
}

/** 继续处理 */
function handleResume(row) {
  resumeForm.value.orderId = row.id
  // resumeForm.value.orderCode = row.workOrderProjectNo
  // resumeDialogVisible.value = true
  ElMessageBox.confirm('确定要恢复工单"' + row.workOrderProjectNo + '"吗？', '提示', {
    confirmButtonText: '确认恢复',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(function() {
    submitResume(row);
  }).then(() => {
    // getList()
    // proxy.$modal.msgSuccess("恢复成功")
  }).catch(() => {})
}

/** 结束工单 */
function handleComplete(row) {
  completeForm.value.orderId = row.id
  completeForm.value.orderCode = row.workOrderProjectNo
  completeDialogVisible.value = true
}

/** 待结单状态：结单按钮 */
function handleFinish(row) {
  // getGxtOrder(row.id).then(response => {
  debugger
    finishForm.value = row
    finishForm.value.orderId = row.id
    finishForm.value.infoEntry = '1'
    if (row.pauseTime && row.restartTime) {
      listAutoMisInfo({
        pauseTime: row.pauseTime,
        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) {
            listGxtOrder({pageNum: 1, pageSize: 10, misNo: row.misNo }).then(response => {
              const gxtOrders = response.rows
              if (gxtOrders.length == 0) {
                finishForm.value.misNo = misInfo[0].misNo
                finishForm.value.realStartTime = misInfo[0].realStartTime
                finishForm.value.realEndTime = misInfo[0].realEndTime
                finishForm.value.workPermitNum = misInfo[0].workPermitNum
                listWorkPerson({misNo: misInfo[0].misNo}).then(response => {
                  finishForm.value.workOrderPersonList = response.rows;
                  if (finishForm.value.workOrderPersonList) {
                    // 查询负责人信息并回填
                    for (const person of finishForm.value.workOrderPersonList) {
                      // 严格判断isLeader为1（兼容数字/字符串类型）
                      if (person.isLeader === 1 || person.isLeader === '1') {
                        finishForm.value.teamLeaderName = person.nickName;
                        break; // 找到后立即停止循环
                      }
                    }
                    const nickNames = finishForm.value.workOrderPersonList
                        .map(person => person.nickName)
                        .join(',');
                    finishForm.value.workGroupMemberName = nickNames
                    // finishDialogVisible.value = true
                  }
                })
              } else {
                ElMessageBox.confirm('未找到匹配的MIS工单，请确认风机停复机时间是否已录入工效通系统或请进入工作票录入方式。', '提示', {
                  confirmButtonText: '确定',
                  showCancelButton: false,
                  type: 'warning'
                }).then(function() {
                  // finishForm.value.infoEntry = '2'
                  infoEntryDisabled.value = true
                }).then(() => {
                }).catch(() => {})
              }
            })
          } else {  // 无工作票号提示
            ElMessageBox.confirm('已匹配到MIS工单，但未关联工作票号，系统无法自动结单，请进入工作票录入方式。', '提示', {
              confirmButtonText: '确定',
              showCancelButton: false,
              type: 'warning'
            }).then(function() {
              // finishForm.value.infoEntry = '2'
              infoEntryDisabled.value = true
            }).then(() => {
            }).catch(() => {})
          }

        } else if (misInfo.length == 0) {
          ElMessageBox.confirm('未找到匹配的MIS工单，请确认风机停复机时间是否已录入工效通系统或请进入工作票录入方式。', '提示', {
            confirmButtonText: '确定',
            showCancelButton: false,
            type: 'warning'
          }).then(function() {
            // finishForm.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() {
        // finishForm.value.infoEntry = '2'
        infoEntryDisabled.value = true
      }).then(() => {
      }).catch(() => {})
      finishForm.value.workPermitNum = null
      finishForm.value.misNo = null
    }
    // if (finishForm.value.infoEntry != null && finishForm.value.infoEntry == '1') {
    //   if (row.misNo != null) {
    //     listMisInfo({misNo: row.misNo}).then(response => {
    //       const misInfo = response.rows
    //       debugger
    //       if (misInfo.length > 0) {
    //         finishForm.value.realStartTime = misInfo[0].realStartTime
    //         finishForm.value.realEndTime = misInfo[0].realEndTime
    //       }
    //     })
    //   }
    //   listWorkPerson({misNo: row.misNo}).then(response => {
    //     finishForm.value.workOrderPersonList = response.rows;
    //     if (finishForm.value.workOrderPersonList) {
    //       const nickNames = finishForm.value.workOrderPersonList
    //           .map(person => person.nickName)
    //           .join(',');
    //       finishForm.value.workGroupMemberName = nickNames
    //       finishDialogVisible.value = true
    //     }
    //   })
    // } else {
    //   finishForm.value.realStartTime = null
    //   finishForm.value.realEndTime = null
    //   finishDialogVisible.value = true
    // }

    finishDialogVisible.value = true
    // 打开对话框后重置表单验证错误
    proxy.$nextTick(() => {
      proxy.$refs["finishRef"]?.clearValidate()
    })
    commonKey++
  // })
}

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

/** 提交结单 */
function submitFinish() {
  proxy.$refs["finishRef"].validate(valid => {
    if (valid) {
      saveFinishWorkOrder()
    }
  })
}

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

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

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

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

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

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


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

// 复运
function handleRestart(row) {
  getGxtOrder(row.id).then(response => {
    restartForm.value = response.data
    restartForm.value.orderId = row.id
    restartDialogVisible.value = true
    // 打开对话框后重置表单验证错误
    proxy.resetForm("restartRef")
  })
}

/** 停机 */
function handleShutdown(row) {
  getGxtOrder(row.id).then(response => {
    shutdownForm.value = response.data
    shutdownForm.value.orderId = row.id
    shutdownDialogVisible.value = true
    // 打开对话框后重置表单验证错误
    proxy.resetForm("shutdownRef")
  })
}

// 提交停机
async function submitShutdownFormParent(data) {
  await shutdownOrder(data)
}

// 在提交停机成功后的回调函数
function handleShutdownSuccess() {
  shutdownDialogVisible.value = false
  getList()
}

/** 提交评分 */
function submitRate() {
  proxy.$refs["rateRef"].validate(valid => {
    if (valid) {
      const gxtWorkOrder = {
        id: rateForm.value.orderId,
        score: rateForm.value.score,
        reviewContent: rateForm.value.reviewContent,
        workOrderStatus: 'to_archive',
        restartTime: rateForm.value.restartTime
      }

      completeWorkOrder(rateForm.value.orderId, gxtWorkOrder).then(response => {
        rateDialogVisible.value = false
        proxy.$modal.msgSuccess("评分成功")
        getList()
      }).catch(error => {
        proxy.$modal.msgError("评分失败：" + (error?.response?.data?.msg || "未知错误"))
      })
    }
  })
}

/** 提交复运 */
async function submitRestart() {
  proxy.$refs["restartRef"].validate(async valid => {
    if (valid) {
      // 判断 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;
        }
      }

      const gxtWorkOrder = {
        id: restartForm.value.orderId,
        restartTime: restartForm.value.restartTime,
        workOrderStatus: 'restarted',
        score: restartForm.value.score,  // 传递 score 字段，供后端判断是否已评分
        lostPower: restartForm.value.lostPower
      }

      completeWorkOrder(restartForm.value.orderId, gxtWorkOrder).then(response => {
        restartDialogVisible.value = false
        proxy.$modal.msgSuccess("复运成功")
        getList()
      }).catch(error => {
        proxy.$modal.msgError("复运失败：" + (error?.response?.data?.msg || "未知错误"))
      })
    }
  })
}

/** 接单 */
function handleAccept(row) {
  getGxtOrder(row.id).then(response => {
    acceptForm.value = response.data
    acceptForm.value.orderId = row.id
    acceptForm.value.teamLeaderId = undefined
    acceptForm.value.teamLeaderName = undefined
    if (row.gxtCenterId) {
      if (lastLoadedCenterId.value !== acceptForm.value.gxtCenterId) {
        allUserList.value = [];
      }

      // 预加载工作负责人列表
      loadQuickTeamLeaderList()
      acceptDialogVisible.value = true
      // 打开对话框后重置表单验证错误
      proxy.resetForm("acceptRef")
    } else {
      proxy.$modal.msgWarning("未找到有效的部门信息，无法加载用户列表");
      acceptDialogVisible.value = true
    }
  })
}

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

/** 工作班成员选择变化 */
function handleMembersChange() {
  // 根据选中的memberIds构建 workOrderPersonList
  finishForm.value.workOrderPersonList = []
  finishForm.value.memberIds.forEach(memberId => {
    const user = userList.value.find(u => u.userId === memberId)
    if (user) {
      finishForm.value.workOrderPersonList.push({
        userId: user.userId,
        nickName: user.nickName,
        orderId: finishForm.value.orderId,
        orderCode: finishForm.value.workOrderProjectNo,
        status: 1
      })
    }
  })
}

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

      acceptOrder(acceptForm.value.orderId, gxtWorkOrder).then(response => {
        proxy.$modal.msgSuccess("接单成功")
        acceptDialogVisible.value = false
        getList()
      }).catch(error => {
        proxy.$modal.msgError("接单失败：" + (error?.response?.data?.msg || "未知错误"))
      })
    }
  })
}

/** 提交开始处理 */
function submitStart() {
  const gxtWorkOrder = {
    id: startForm.value.orderId,
    workOrderStatus: 'processing'
  }

  startWorkOrder(startForm.value.orderId, gxtWorkOrder).then(response => {
    proxy.$modal.msgSuccess("开始处理成功")
    startDialogVisible.value = false
    getList()
  }).catch(error => {
    proxy.$modal.msgError("开始处理失败：" + (error?.response?.data?.msg || "未知错误"))
  })
}

/** 提交挂起 */
function submitSuspend() {
  proxy.$refs["suspendRef"].validate(valid => {
    if (valid) {
      const gxtWorkOrder = {
        id: suspendForm.value.orderId,
        suspendReason: suspendForm.value.suspendReason,
        remark: suspendForm.value.remark
      }

      suspendWorkOrder(suspendForm.value.orderId, gxtWorkOrder).then(response => {
        proxy.$modal.msgSuccess("挂起申请提交成功")
        suspendDialogVisible.value = false
        getList()
      }).catch(error => {
        proxy.$modal.msgError("挂起申请失败：" + (error?.response?.data?.msg || "未知错误"))
      })
    }
  })
}

/** 提交继续处理 */
function submitResume(row) {
  const gxtWorkOrder = {
    id: resumeForm.value.orderId,
    workOrderStatus: row.workOrderStatus == 'auto_suspend'? 'assigned' : 'to_finish'
  }

  resumeWorkOrder(resumeForm.value.orderId, gxtWorkOrder).then(response => {
    proxy.$modal.msgSuccess("恢复成功")
    resumeDialogVisible.value = false
    getList()
  }).catch(error => {
    proxy.$modal.msgError("恢复失败：" + (error?.response?.data?.msg || "未知错误"))
  })
}

/** 提交挂起审批 */
function submitApprove(approvalStatusValue) {
  approveForm.value.workOrderStatus = approvalStatusValue
  proxy.$refs["approveRef"].validate(valid => {
    if (valid) {
      approveWorkOrder(approveForm.value.orderId, approveForm.value).then(response => {
        const msg = approveForm.value.workOrderStatus === 'suspended' ? '挂起审批通过' : '挂起审批驳回'
        proxy.$modal.msgSuccess(msg + "成功")
        approveDialogVisible.value = false
        getList()
      }).catch(error => {
        proxy.$modal.msgError("审批失败：" + (error?.response?.data?.msg || "未知错误"))
      })
    }
  })
}

/** 提交暂停 */
function submitPause() {
  proxy.$refs["pauseRef"].validate(valid => {
    if (valid) {
      const gxtWorkOrder = {
        id: pauseForm.value.orderId,
        pauseReason: pauseForm.value.pauseReason,
        remark: pauseForm.value.remark
      }

      pauseWorkOrder(pauseForm.value.orderId, gxtWorkOrder).then(response => {
        proxy.$modal.msgSuccess("暂停成功")
        pauseDialogVisible.value = false
        getList()
      }).catch(error => {
        proxy.$modal.msgError("暂停失败：" + (error?.response?.data?.msg || "未知错误"))
      })
    }
  })
}

/** 审批挂起申请 */
function handleApprove(row) {
  getGxtOrder(row.id).then(response => {
    approveForm.value = response.data
    approveForm.value.orderId = row.id
    approveForm.value.rejectionReason = undefined
    approveDialogVisible.value = true
    // 打开对话框后重置表单验证错误
    proxy.resetForm("approveRef")
  })
}

/** 作废工单操作 */
function handleInvalidate(row) {
  getGxtOrder(row.id).then(response => {
    invalidateForm.value = response.data
    invalidateForm.value.id = row.id
    invalidateForm.value.invalidReason = undefined
    invalidateDialogVisible.value = true
    // 重置表单验证
    proxy.$nextTick(() => {
      proxy.$refs["invalidateRef"]?.clearValidate()
    })
  })
}

/** 提交作废 */
function submitInvalidate() {
  proxy.$refs["invalidateRef"].validate(valid => {
    if (valid) {
      const gxtWorkOrder = {
        id: invalidateForm.value.id,
        invalidReason: invalidateForm.value.invalidReason,
        workOrderStatus: 'invalid'
      }

      invalidateGxtOrder(gxtWorkOrder).then(response => {
        proxy.$modal.msgSuccess("作废成功")
        invalidateDialogVisible.value = false
        getList()
      }).catch(error => {
        proxy.$modal.msgError("作废失败：" + (error?.response?.data?.msg || "未知错误"))
      })
    }
  })
}

/** 获取操作类型名称 */
function getActionTypeName(actionType) {
  const actionTypeMap = {
    'create': '创建工单',
    'assign': '派单',
    'accept': '接单',
    'process': '处理',
    'pause': '暂停',
    'suspend': '挂起',
    'restart': '重启',
    'approve': '审批',
    'complete': '完成'
  }
  return actionTypeMap[actionType] || actionType
}

/** 获取状态名称 */
function getStatusName(status) {
  const statusMap = {
    'draft': '草稿',
    'to_assign': '待派单',
    'assigned': '已派单',
    'accepted': '已接单',
    'processing': '处理中',
    'paused': '暂停中',
    'to_approve': '待审批',
    'suspended': '已挂起',
    'completed': '已完成'
  }
  return statusMap[status] || status
}

/** 判断是否为图片文件 */
function isImageFile(fileName) {
  if (!fileName) return false
  const ext = fileName.split('.').pop().toLowerCase()
  const imageExts = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']
  return imageExts.includes(ext)
}

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

/** 片段导入按點操作 */
function handleImport(type) {
  if (type === 'person') {
    personUpload.title = "人员导入"
    personUpload.open = true
    personUpload.selectedFile = null
  } else {
    upload.title = "工单导入"
    upload.open = true
    upload.selectedFile = null
  }
}

/** 清理模板操作 */
function importTemplate() {
  proxy.download("gxt/order/importTemplate", {
  }, `gxtOrder_template_${new Date().getTime()}.xlsx`)
}

/** 清理模板操作 */
function importPersonTemplate() {
  proxy.download("gxt/workOrderPerson/importTemplate", {
  }, `gxtOrderPerson_template_${new Date().getTime()}.xlsx`)
}

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

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

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

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

/** 人员文件上传中处理 */
const handlePersonFileUploadProgress = (event, file, fileList) => {
  personUpload.isUploading = true
}

/** 人员文件选择处理 */
const handlePersonFileChange = (file, fileList) => {
  personUpload.selectedFile = file
}

/** 人员文件删除处理 */
const handlePersonFileRemove = (file, fileList) => {
  personUpload.selectedFile = null
}

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

/** 提交人员文件 */
function submitPersonFileForm() {
  const file = personUpload.selectedFile
  if (!file || file.length === 0 || !file.name.toLowerCase().endsWith('.xls') && !file.name.toLowerCase().endsWith('.xlsx')) {
    proxy.$modal.msgError("请选择后缀为 \"xls\"或\"xlsx\"的文件。")
    return
  }
  proxy.$refs["personUploadRef"].submit()
}

/** 导出按點操作 */
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/order/export', exportParams, `gxtOrder_${new Date().getTime()}.xlsx`);

  showExportFieldsDialog.value = false;
}

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

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 = [];
  }
}

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

/** 打开MIS信息选择对话框 */
function handleSelectMisInfo() {
  misInfoSelectVisible.value = true
}

function handleSelectMisInfo2() {
  debugger
  misInfoSelectVisible2.value = true
}

/** 设备MIS信息回调 */
function onMisInfoSelected(row) {
  if (row) {
    listGxtOrder({pageNum: 1, pageSize: 10, misNo: row.misNo }).then(response => {
      const  gxtOrders= response.rows
      debugger
      if (gxtOrders.length > 0) {
        if (form.value.id == null) {
          proxy.$modal.msgWarning('选择工单已存在！请重新选择！')
          return
        } else {
          if (gxtOrders[0].id != form.value.id) {
            proxy.$modal.msgWarning('选择工单已存在！请重新选择！')
            return
          }
        }
      }
      form.value.misNo = row.misNo
      form.value.content = row.content
      form.value.realStartTime = row.realStartTime
      form.value.realEndTime = row.realEndTime
      form.value.workPermitNum = row.workPermitNum
      // form.value.planStartTime = row.planStartTime
      // form.value.planEndTime = row.planEndTime
      if (!form.value.pcsDeviceId) {
        form.value.pcsDeviceName = row.pcsDeviceName
        form.value.pcsStationName = row.pcsStationName
        listEquipment({station: row.pcsStationName, equipmentCode: row.pcsDeviceName}).then(response => {
          const equipments = response.rows
          if (equipments) {
            form.value.pcsDeviceId = equipments[0].equipmentId
            form.value.gxtCenter = equipments[0].maintenanceCenter
            form.value.brand = equipments[0].brand
            form.value.model = equipments[0].model
          }
        });
      }
      misInfoSelectVisible.value = false
    })
  }
}

function onMisInfoSelected2(row) {
  if (row) {
    listGxtOrder({pageNum: 1, pageSize: 10, misNo: row.misNo }).then(response => {
      const  gxtOrders= response.rows
      debugger
      if (gxtOrders.length > 0) {
        if (finishForm.value.id == null) {
          proxy.$modal.msgWarning('选择工单已存在！请重新选择！')
          return
        } else {
          if (gxtOrders[0].id != form.value.id) {
            proxy.$modal.msgWarning('选择工单已存在！请重新选择！')
            return
          }
        }
      }
      // finishForm.value.misNo = row.misNo
      // finishForm.value.content = row.content
      // finishForm.value.realStartTime = row.realStartTime
      // finishForm.value.realEndTime = row.realEndTime
      // finishForm.value.workPermitNum = row.workPermitNum
      // 使用展开运算符创建新对象以确保响应式更新
      finishForm.value = {
        ...finishForm.value,
        misNo: row.misNo,
        realStartTime: row.realStartTime,
        realEndTime: row.realEndTime,
        content: row.content,
        workPermitNum: row.workPermitNum
      };
      // finalizeFormData.value.content = row.content
      // 使用从属性传入的listWorkPerson方法
      if (typeof listWorkPerson === 'function') {
        listWorkPerson({ misNo: row.misNo }).then(response => {
          debugger
          const updatedData = {
            ...finishForm.value,
            workOrderPersonList: response.rows
          };
          if (response.rows) {
            // 查找 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
          }
          finishForm.value = updatedData;
        })
      }
      misInfoSelectVisible2.value = false
    })
  }
}

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

/** 打开设备选择对话框 */
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
  commonKey++
}
const handleInfoEntryChange = (val) => {
  form.value.content = undefined;
  // 选中2工作票编号时修改其他值
  if (val === '2') {
    form.value.misOrderNo = undefined;
    form.value.realStartTime = undefined;
    form.value.realEndTime = undefined;
  } else {
    form.value.workPermitNum = undefined;
  }
};
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 = finishForm.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 = finishForm.value.acceptTime; // 脚本中用 .value
  const startStr = finishForm.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 workPermitNumProxy = computed({
  get() {
    return form.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. 写回表单
    form.value.workPermitNum = trimmed
  }
})

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

getList()
</script>
<style scoped>

.approve-dialog .el-dialog {
  max-height: 500px;
  overflow-y: auto;
  padding-right: 10px;
}

.approve-dialog .el-dialog__body {
  max-height: calc(600px - 120px); /* 减去头部和底部高度 */
  overflow-y: auto;
}
.text-gray-500 {
  color: #6b7280;
}
.mb-2 {
  margin-bottom: 0.5rem;
}
.mb-3 {
  margin-bottom: 0.75rem;
}
.card-header {
  font-weight: bold;
  font-size: 16px;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

/* 附件列表样式 */
.attachment-list {
  padding: 10px 0;
}

.attachment-item {
  display: flex;
  align-items: center;
  padding: 12px;
  border: 1px solid #e0e7ff;
  border-radius: 6px;
  background-color: #f9fafb;
  margin-bottom: 8px;
}

.attachment-icon {
  flex-shrink: 0;
  margin-right: 12px;
  width: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.attachment-info {
  flex: 1;
  min-width: 0;
}

.attachment-info .text-sm {
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

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