<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">
        <el-input
          v-model="queryParams.workOrderProjectNo"
          placeholder="请输入工单编码"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="维保类型" prop="inspectionTypeId" label-position="top">
        <el-select v-model="queryParams.inspectionTypeId" 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-input
          v-model="queryParams.gxtCenter"
          placeholder="请输入维保中心"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="风电场" prop="pcsStationName" label-position="top">
        <el-input
          v-model="queryParams.pcsStationName"
          placeholder="请输入风电场"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工单状态" prop="workOrderStatus" label-position="top">
        <el-select v-model="queryParams.workOrderStatus" placeholder="请选择工单状态" clearable>
          <el-option
              v-for="dict in gxt_work_order_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
<!--      <el-form-item label="工单来源" prop="orderSource">-->
<!--        <el-input-->
<!--          v-model="queryParams.orderSource"-->
<!--          placeholder="请输入工单来源"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
    </el-form>
    <div style="float: right;">
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
    </div>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['worklog:Gxt:order:add']"
        >手动创建</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['worklog:Gxt: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:order:remove']"
        >删除</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">
      <el-table-column label="工单编码" align="center" prop="workOrderProjectNo" width="140" />
      <el-table-column label="工单状态" align="center" prop="workOrderStatus" 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="pcsDeviceName" width="120" :show-overflow-tooltip="true" />
      <el-table-column label="维保中心" align="center" prop="gxtCenter" width="120" :show-overflow-tooltip="true" />
      <el-table-column label="风电场" align="center" prop="pcsStationName" width="120" :show-overflow-tooltip="true" />
      <el-table-column label="风机品牌" align="center" prop="brand" width="140" :show-overflow-tooltip="true" />
      <el-table-column label="风机型号" align="center" prop="model" width="140" :show-overflow-tooltip="true" />
      <el-table-column label="维保计划编号" align="center" prop="workPlanNo" width="140" />
      <el-table-column label="计划检修日期" align="center" prop="planStartTime" width="160">
        <template #default="scope">
          <span>{{ parseTime(scope.row.planStartTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="计划结束时间" align="center" prop="planEndTime" width="160">-->
<!--        <template #default="scope">-->
<!--          <span>{{ parseTime(scope.row.planEndTime, '{y}-{m}-{d} {h}:{i}') }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="工单来源" align="center" prop="orderSource" width="100" />-->
      <el-table-column label="派单时间" align="center" prop="assignTime" width="100" >
        <template #default="scope">
          <span>{{ parseTime(scope.row.assignTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="派单人" align="center" prop="assignUserName" width="100" />
      <el-table-column label="接单人" align="center" prop="acceptUserName" width="100" />
      <el-table-column label="接单时间" align="center" prop="acceptTime" width="100">
        <template #default="scope">
          <span>{{ parseTime(scope.row.acceptTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="班组组长" align="center" prop="teamLeaderName" width="100" />-->
<!--      <el-table-column label="工作组成员" align="center" prop="workGroupMemberName" width="100" />-->
      <el-table-column label="操作" align="left" width="200" class-name="small-padding fixed-width" fixed="right" >
        <template #default="scope">
          <!-- 草稿状态：显示编辑和删除按钮 -->
          <el-button link type="primary" @click="handleUpdate(scope.row)" v-hasPermi="['worklog:Gxt:order:edit']" v-if="scope.row.workOrderStatus === 'draft'">
            <i class="fa fa-edit"></i>编辑
          </el-button>
<!--          <el-button link type="danger" @click="handleDelete(scope.row)" v-if="scope.row.workOrderStatus === 'draft'">-->
<!--            <i class="fa fa-trash"></i>删除-->
<!--          </el-button>-->

          <!-- 待派单状态：只显示派单按钮 -->
          <el-button link type="primary" @click="handleAssign(scope.row)" v-if="scope.row.workOrderStatus === 'to_assign'">
            <i class="fa fa-user-plus"></i>派单
          </el-button>

          <!-- 已派单状态：只显示确认按钮 -->
          <el-button link type="success" @click="handleAccept(scope.row)" v-if="scope.row.workOrderStatus === 'assigned'">
            <i class="fa fa-check"></i>确认
          </el-button>

          <!-- 已接单状态：显示开始、暂停、挂起按钮 -->
          <el-button link type="success" @click="handleStart(scope.row)" v-if="scope.row.workOrderStatus === 'accepted'">
            <i class="fa fa-play"></i>开始
          </el-button>
          <el-button link type="warning" @click="handlePause(scope.row)" v-if="scope.row.workOrderStatus === 'accepted'">
            <i class="fa fa-pause"></i>暂停
          </el-button>
          <el-button link type="danger" @click="handleSuspend(scope.row)" v-if="scope.row.workOrderStatus === 'accepted'">
            <i class="fa fa-stop"></i>挂起
          </el-button>

          <!-- 处理中状态：显示暂停、挂起按钮 -->
          <el-button link type="warning" @click="handlePause(scope.row)" v-if="scope.row.workOrderStatus === 'processing'">
            <i class="fa fa-pause"></i>暂停
          </el-button>
          <el-button link type="danger" @click="handleSuspend(scope.row)" v-if="scope.row.workOrderStatus === 'processing'">
            <i class="fa fa-stop"></i>挂起
          </el-button>

          <!-- 暂停中状态：显示恢复按钮 -->
          <el-button link type="success" @click="handleResume(scope.row)" v-if="scope.row.workOrderStatus === 'paused'">
            <i class="fa fa-play"></i>恢复
          </el-button>

          <!-- 已挂起状态：显示重启按钮 -->
          <el-button link type="primary" @click="handleRestart(scope.row)" v-if="scope.row.workOrderStatus === 'suspended'">
            <i class="fa fa-refresh"></i>重启
          </el-button>

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

          <!-- 已完成状态：不显示操作按钮 -->

          <!-- 查看按钮对所有状态都显示 -->
          <el-button link type="info" @click="handleDetail(scope.row)" v-hasPermi="['worklog:Gxt:order:query']">
            <i class="fa fa-eye"></i>查看
          </el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 添加或修改维保工单对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="orderRef" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="工单编码" prop="workOrderProjectNo">
              <el-input v-model="form.workOrderProjectNo" placeholder="请输入工单编码" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="风机编号" prop="pcsDeviceName">
              <el-input v-model="form.pcsDeviceName" placeholder="请输入风机编号" disabled/>
            </el-form-item>
          </el-col>
<!--          <el-col :span="12">-->
<!--            <el-form-item label="工单状态" prop="workOrderStatus">-->
<!--              <el-select v-model="form.workOrderStatus" placeholder="请选择工单状态" 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="维保类型" prop="inspectionTypeId">
              <el-select v-model="form.inspectionTypeId" placeholder="请选择维保类型">
                <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-col :span="12">
            <el-form-item label="维保中心" prop="gxtCenter">
              <el-input v-model="form.gxtCenter" placeholder="请输入维保中心" disabled/>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="风电场" prop="pcsStationName">
              <el-input v-model="form.pcsStationName" placeholder="请输入风电场" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="风机品牌" prop="brand">
              <el-input v-model="form.brand" placeholder="请输入风机品牌" disabled/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
<!--          <el-col :span="12">-->
<!--            <el-form-item label="风机型号" prop="model">-->
<!--              <el-input v-model="form.model" placeholder="请输入风机型号" disabled/>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
          <el-col :span="12">
            <el-form-item label="维保计划编号" prop="workPlanNo">
              <el-input v-model="form.workPlanNo" placeholder="请输入维保计划编号" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划检修日期" prop="planStartTime">
              <el-date-picker
                  v-model="form.planStartTime"
                  type="datetime"
                  placeholder="请选择计划检修日期"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  style="width: 100%"
                  disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
<!--        <el-row>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="预计工时(小时)" prop="planHour">-->
<!--              <el-input-number v-model="form.planHour" placeholder="请输入预计工时" :precision="2" :step="0.5" style="width: 100%" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--        </el-row>-->
        <el-row>
          <el-col :span="24">
            <el-form-item label="维保内容" prop="content">
              <el-input v-model="form.content" type="textarea" placeholder="请输入维保内容" />
            </el-form-item>
          </el-col>
        </el-row>
<!--        <el-row>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="故障代码" prop="faultCode">-->
<!--              <el-input v-model="form.faultCode" placeholder="请输入故障代码" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="优先级" prop="priorityType">-->
<!--              <el-input v-model="form.priorityType" placeholder="请输入优先级" type="number" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--        </el-row>-->
<!--        <el-row>-->
<!--          <el-col :span="24">-->
<!--            <el-form-item label="故障描述" prop="faultDesc">-->
<!--              <el-input v-model="form.faultDesc" type="textarea" placeholder="请输入故障描述" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--        </el-row>-->
<!--        <el-row>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="工单类型" prop="orderType">-->
<!--              <el-input v-model="form.orderType" placeholder="请输入工单类型" type="number" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--        </el-row>-->
        <el-row>
          <el-col :span="24">
            <el-form-item label="保存选项">
              <el-radio-group v-model="form.workOrderStatus" class="ml-4">
                <el-radio label="draft">保存（继续编辑）</el-radio>
                <el-radio label="to_assign">保存并提交（待派单）</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
<!--        <el-row>-->
<!--          <el-col :span="24">-->
<!--            <el-form-item label="备注" prop="remark">-->
<!--              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--        </el-row>-->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 派单对话框 -->
    <el-dialog title="派单" v-model="assignDialogVisible" width="500px" append-to-body>
      <el-form ref="assignRef" :model="assignForm" :rules="assignRules" label-width="100px">
        <el-form-item label="派单给" prop="assignType">
          <el-radio-group v-model="assignForm.assignType">
            <el-radio value="teamLeader">班组组长</el-radio>
            <el-radio value="workGroupMember">工作组成员</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="assignForm.assignType === 'teamLeader'" label="班组组长" prop="teamLeaderId">
          <el-select v-model="assignForm.teamLeaderId" placeholder="请选择班组组长" style="width: 100%" @change="handleTeamLeaderChange">
            <el-option
              v-for="user in userList"
              :key="user.userId"
              :label="user.userName"
              :value="user.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="assignForm.assignType === 'workGroupMember'" label="工作组成员" prop="workGroupMemberId">
          <el-select v-model="assignForm.workGroupMemberId" placeholder="请选择工作组成员" style="width: 100%" @change="handleWorkGroupMemberChange">
            <el-option
              v-for="user in userList"
              :key="user.userId"
              :label="user.userName"
              :value="user.userId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitAssign">确 定</el-button>
          <el-button @click="assignDialogVisible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 挂起对话框 -->
    <el-dialog title="挂起工单" v-model="suspendDialogVisible" width="500px" append-to-body>
      <el-form ref="suspendRef" :model="suspendForm" :rules="suspendRules" label-width="100px">
        <el-form-item label="挂起原因" prop="suspendReason">
          <el-input v-model="suspendForm.suspendReason" type="textarea" placeholder="请输入挂起原因" :rows="4" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitSuspend">确 定</el-button>
          <el-button @click="suspendDialogVisible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 接单对话框 -->
    <el-dialog :title="`接单 - ${acceptForm.workOrderProjectNo}`" v-model="acceptDialogVisible" width="800px" append-to-body>
      <el-form ref="acceptRef" :model="acceptForm" :rules="acceptRules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="工单编码">
              <el-input v-model="acceptForm.workOrderProjectNo" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="风机编号">
              <el-input v-model="acceptForm.pcsDeviceName" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="工单类型">
              <el-input v-model="acceptForm.orderType" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="派单人">
              <el-input v-model="acceptForm.assignUserName" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="派单时间">
              <el-input v-model="acceptForm.assignTime" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划检修日期">
              <el-input v-model="acceptForm.planStartTime" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="工作负责人" prop="responsiblePersonId">
              <el-select v-model="acceptForm.responsiblePersonId" placeholder="请选择工作负责人" style="width: 100%" @change="(userId) => acceptForm.responsiblePersonName = 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-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="检修人员" prop="memberIds">
              <el-checkbox-group v-model="acceptForm.memberIds" style="width: 100%" @change="handleMembersChange">
                <el-row :gutter="10">
                  <el-col :span="8" v-for="user in userList" :key="user.userId">
                    <el-checkbox :label="user.userId">{{ user.nickName }}</el-checkbox>
                  </el-col>
                </el-row>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitAccept">确认接单</el-button>
          <el-button @click="acceptDialogVisible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 流转记录对话框 -->
    <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}:{s}')"
          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>

    <!-- 详情对话框 -->
    <el-dialog title="工单详情" v-model="detailDialogVisible" width="900px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="工单编码">{{ detailData.workOrderProjectNo }}</el-descriptions-item>
        <el-descriptions-item label="工单状态">
          <dict-tag :options="gxt_work_order_status" :value="detailData.workOrderStatus"/>
        </el-descriptions-item>
        <el-descriptions-item label="维保中心ID">{{ detailData.gxtCenterId }}</el-descriptions-item>
        <el-descriptions-item label="维保中心">{{ detailData.gxtCenter }}</el-descriptions-item>
        <el-descriptions-item label="风电场ID">{{ detailData.pcsStationId }}</el-descriptions-item>
        <el-descriptions-item label="风电场">{{ detailData.pcsStationName }}</el-descriptions-item>
        <el-descriptions-item label="风机设备ID">{{ detailData.pcsDeviceId }}</el-descriptions-item>
        <el-descriptions-item label="风机编号">{{ detailData.pcsDeviceName }}</el-descriptions-item>
        <el-descriptions-item label="风机品牌">{{ detailData.brand }}</el-descriptions-item>
        <el-descriptions-item label="风机型号">{{ detailData.model }}</el-descriptions-item>
        <el-descriptions-item label="检查类型">{{ detailData.inspectionTypeId }}</el-descriptions-item>
        <el-descriptions-item label="维保计划编号">{{ detailData.workPlanNo }}</el-descriptions-item>
        <el-descriptions-item label="计划检修日期">{{ parseTime(detailData.planStartTime, '{y}-{m}-{d} {h}:{i}') }}</el-descriptions-item>
        <el-descriptions-item label="计划结束时间">{{ parseTime(detailData.planEndTime, '{y}-{m}-{d} {h}:{i}') }}</el-descriptions-item>
        <el-descriptions-item label="工单来源">{{ detailData.orderSource }}</el-descriptions-item>
        <el-descriptions-item label="派单时间">{{ parseTime(detailData.assignTime, '{y}-{m}-{d} {h}:{i}') }}</el-descriptions-item>
        <el-descriptions-item label="派单人">{{ detailData.assignUserName }}</el-descriptions-item>
        <el-descriptions-item label="接单时间">{{ parseTime(detailData.acceptTime, '{y}-{m}-{d} {h}:{i}') }}</el-descriptions-item>
        <el-descriptions-item label="接单人">{{ detailData.acceptUserName }}</el-descriptions-item>
        <el-descriptions-item label="实际开始时间" v-if="detailData.realStartTime">{{ parseTime(detailData.realStartTime, '{y}-{m}-{d} {h}:{i}') }}</el-descriptions-item>
        <el-descriptions-item label="实际结束时间" v-if="detailData.realEndTime">{{ parseTime(detailData.realEndTime, '{y}-{m}-{d} {h}:{i}') }}</el-descriptions-item>
        <el-descriptions-item label="班组组长ID">{{ detailData.teamLeaderId }}</el-descriptions-item>
        <el-descriptions-item label="班组组长">{{ detailData.teamLeaderName }}</el-descriptions-item>
        <el-descriptions-item label="工作组成员ID">{{ detailData.workGroupMemberId }}</el-descriptions-item>
        <el-descriptions-item label="工作组成员">{{ detailData.workGroupMemberName }}</el-descriptions-item>
        <el-descriptions-item label="挂起原因" :span="2" v-if="detailData.suspendReason">{{ detailData.suspendReason }}</el-descriptions-item>
        <el-descriptions-item label="挂起时间" v-if="detailData.suspendTime">{{ parseTime(detailData.suspendTime, '{y}-{m}-{d} {h}:{i}') }}</el-descriptions-item>
        <el-descriptions-item label="暂停原因" :span="2" v-if="detailData.pauseReason">{{ detailData.pauseReason }}</el-descriptions-item>
        <el-descriptions-item label="暂停时间" v-if="detailData.pauseTime">{{ parseTime(detailData.pauseTime, '{y}-{m}-{d} {h}:{i}') }}</el-descriptions-item>
        <el-descriptions-item label="重启时间" v-if="detailData.restartTime">{{ parseTime(detailData.restartTime, '{y}-{m}-{d} {h}:{i}') }}</el-descriptions-item>
        <el-descriptions-item label="完成时间" v-if="detailData.completeTime">{{ parseTime(detailData.completeTime, '{y}-{m}-{d} {h}:{i}') }}</el-descriptions-item>
        <el-descriptions-item label="预计工时（小时）">{{ detailData.planHour }}</el-descriptions-item>
        <el-descriptions-item label="维保内容" :span="2">{{ detailData.content }}</el-descriptions-item>
        <el-descriptions-item label="故障代码">{{ detailData.faultCode }}</el-descriptions-item>
        <el-descriptions-item label="优先级">{{ detailData.priorityType }}</el-descriptions-item>
        <el-descriptions-item label="故障描述" :span="2">{{ detailData.faultDesc }}</el-descriptions-item>
        <el-descriptions-item label="工单类型">{{ detailData.orderType }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ detailData.remark }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup name="GxtOrder">
import {
  listGxtOrder,
  getGxtOrder,
  delGxtOrder,
  addGxtOrder,
  updateGxtOrder,
  assignToTeamLeader,
  acceptByTeamLeader,
  assignToWorkGroupMember,
  acceptByWorkGroupMember,
  suspendWorkOrder,
  restartWorkOrder,
  completeWorkOrder,
  getWorkOrderFlow,
  acceptOrder,
  // startWorkOrder,
  // pauseWorkOrder,
  // resumeWorkOrder,
  // approveWorkOrder
} from "@/api/gxt/gxtOrder"
import { listUser } from "@/api/system/user"
import { getDicts } from "@/api/system/dict/data"

const { proxy } = getCurrentInstance()
const { gxt_work_order_status, gxt_inspection_type } = proxy.useDict("gxt_work_order_status", "gxt_inspection_type")

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 flowDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const acceptDialogVisible = ref(false)
const userList = ref([])
const flowList = ref([])
const detailData = ref({})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    workOrderProjectNo: undefined,
    workOrderStatus: undefined,
    gxtCenter: undefined,
    pcsStationName: undefined,
    orderSource: undefined
  },
  rules: {
    workOrderProjectNo: [{ required: true, message: "工单编码不能为空", trigger: "blur" }],
    workOrderStatus: [{ required: true, message: "工单状态不能为空", trigger: "change" }],
    gxtCenter: [{ required: true, message: "维保中心不能为空", trigger: "blur" }],
    pcsStationName: [{ required: true, message: "风电场不能为空", 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,
    suspendReason: undefined
  },
  suspendRules: {
    suspendReason: [{ required: true, message: "请输入挂起原因", trigger: "blur" }]
  },
  acceptForm: {
    orderId: undefined,
    orderCode: undefined,
    workOrderProjectNo: undefined,
    pcsDeviceName: undefined,
    orderType: undefined,
    assignUserName: undefined,
    assignTime: undefined,
    planStartTime: undefined,
    responsiblePersonId: undefined,
    responsiblePersonName: undefined,
    memberIds: [],
    workOrderPersonList: []
  },
  acceptRules: {
    responsiblePersonId: [{ required: true, message: "请选择工作负责人", trigger: "change" }],
    memberIds: [{ required: true, message: "请至少选择一名检修人员", trigger: "change" }]
  }
})

const { queryParams, form, rules, assignForm, assignRules, suspendForm, suspendRules, acceptForm, acceptRules } = toRefs(data)

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

/** 取消按钮 */
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,
    inspectionTypeId: 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()
  open.value = true
  title.value = "添加维保工单"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const id = row.id || ids.value
  getGxtOrder(id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改维保工单"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["orderRef"].validate(valid => {
    if (valid) {
      if (form.value.id != undefined) {
        updateGxtOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addGxtOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

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

/** 详情按钮操作 */
function handleDetail(row) {
  getGxtOrder(row.id).then(response => {
    detailData.value = response.data
    detailDialogVisible.value = true
  })
}

/** 开始处理 */
function handleStart(row) {
  proxy.$modal.confirm('确认开始处理工单？').then(function() {
    // return startWorkOrder(row.id)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("工单已开始处理")
  }).catch(() => {})
}

/** 暂停处理 */
function handlePause(row) {
  proxy.$modal.confirm('确认暂停工单？').then(function() {
    // return pauseWorkOrder(row.id)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("工单已暂停")
  }).catch(() => {})
}

/** 恢复处理 */
function handleResume(row) {
  proxy.$modal.confirm('确认恢复工单？').then(function() {
    // return resumeWorkOrder(row.id)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("工单已恢复")
  }).catch(() => {})
}

/** 审批工单 */
function handleApprove(row) {
  proxy.$modal.confirm('确认审批通过工单？').then(function() {
    // return approveWorkOrder(row.id)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("工单审批通过")
  }).catch(() => {})
}

/** 下拉菜单命令处理 */
function handleCommand(command, row) {
  switch (command) {
    case 'assign':
      handleAssign(row)
      break
    case 'accept':
      handleAccept(row)
      break
    case 'suspend':
      handleSuspend(row)
      break
    case 'restart':
      handleRestart(row)
      break
    case 'complete':
      handleComplete(row)
      break
    case 'flow':
      handleFlow(row)
      break
  }
}

/** 派单 */
function handleAssign(row) {
  assignForm.value.orderId = row.id
  assignForm.value.assignType = 'teamLeader'
  assignForm.value.teamLeaderId = undefined
  assignForm.value.workGroupMemberId = undefined
  // 获取用户列表
  listUser({ pageNum: 1, pageSize: 100 }).then(response => {
    userList.value = response.rows
    assignDialogVisible.value = true
  })
}

/** 班组组长变更 */
function handleTeamLeaderChange(userId) {
  const user = userList.value.find(u => u.userId === userId)
  if (user) {
    assignForm.value.teamLeaderName = user.userName
  }
}

/** 工作组成员变更 */
function handleWorkGroupMemberChange(userId) {
  const user = userList.value.find(u => u.userId === userId)
  if (user) {
    assignForm.value.workGroupMemberName = user.userName
  }
}

/** 提交派单 */
function submitAssign() {
  proxy.$refs["assignRef"].validate(valid => {
    if (valid) {
      if (assignForm.value.assignType === 'teamLeader') {
        assignToTeamLeader(assignForm.value.orderId, assignForm.value.teamLeaderId, assignForm.value.teamLeaderName).then(response => {
          proxy.$modal.msgSuccess("派单成功")
          assignDialogVisible.value = false
          getList()
        })
      } else {
        assignToWorkGroupMember(assignForm.value.orderId, assignForm.value.workGroupMemberId, assignForm.value.workGroupMemberName).then(response => {
          proxy.$modal.msgSuccess("派单成功")
          assignDialogVisible.value = false
          getList()
        })
      }
    }
  })
}

/** 接单 */
function handleAccept(row) {
  acceptForm.value.orderId = row.id
  acceptForm.value.orderCode = row.orderCode
  acceptForm.value.workOrderProjectNo = row.workOrderProjectNo
  acceptForm.value.pcsDeviceName = row.pcsDeviceName
  acceptForm.value.orderType = row.orderType
  acceptForm.value.assignUserName = row.assignUserName
  acceptForm.value.assignTime = row.assignTime
  acceptForm.value.planStartTime = row.planStartTime
  acceptForm.value.responsiblePersonId = undefined
  acceptForm.value.responsiblePersonName = undefined
  acceptForm.value.memberIds = []
  // 根据风电场ID查询该场站的用户列表
  listUser({ pageNum: 1, pageSize: 100, deptId: row.pcsStationId }).then(response => {
    userList.value = response.rows
    acceptDialogVisible.value = true
    // 打开对话框后重置表单验证错误
    proxy.$nextTick(() => {
      proxy.$refs["acceptRef"]?.clearValidate()
    })
  })
}

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

/** 检修人员选择变化 */
function handleMembersChange() {
  // 根据选中的memberIds构建 workOrderPersonList
  acceptForm.value.workOrderPersonList = []
  acceptForm.value.memberIds.forEach(memberId => {
    const user = userList.value.find(u => u.userId === memberId)
    if (user) {
      acceptForm.value.workOrderPersonList.push({
        userId: user.userId,
        nickName: user.nickName,
        orderId: acceptForm.value.orderId,
        orderCode: acceptForm.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.responsiblePersonId,
        acceptUserName: acceptForm.value.responsiblePersonName,
        workOrderPersonList: acceptForm.value.workOrderPersonList
      }
      
      acceptOrder(acceptForm.value.orderId, gxtWorkOrder).then(response => {
        proxy.$modal.msgSuccess("接单成功")
        acceptDialogVisible.value = false
        getList()
      }).catch(error => {
        proxy.$modal.msgError("接单失败：" + (error?.response?.data?.msg || "未知错误"))
      })
    }
  })
}

/** 提交挂起 */
function submitSuspend() {
  proxy.$refs["suspendRef"].validate(valid => {
    if (valid) {
      suspendWorkOrder(suspendForm.value.orderId, suspendForm.value.suspendReason).then(response => {
        proxy.$modal.msgSuccess("挂起成功")
        suspendDialogVisible.value = false
        getList()
      })
    }
  })
}

/** 重启 */
function handleRestart(row) {
  proxy.$modal.confirm('确认重启工单？').then(function() {
    return restartWorkOrder(row.id)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("重启成功")
  }).catch(() => {})
}

/** 完成 */
function handleComplete(row) {
  proxy.$modal.confirm('确认完成工单？').then(function() {
    return completeWorkOrder(row.id)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("工单已完成")
  }).catch(() => {})
}

/** 流转记录 */
function handleFlow(row) {
  getWorkOrderFlow(row.id).then(response => {
    flowList.value = response.data
    flowDialogVisible.value = true
  })
}

/** 获取操作类型名称 */
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
}

getList()
</script>
