<template>
  <div class="plan-center app-container">
    <el-card class="filter-card" shadow="never">
      <el-form
        ref="queryForm"
        :model="queryParams"
        :inline="true"
        label-width="90px"
        size="small"
        v-show="showSearch"
      >
        <el-form-item label="预案名称" prop="planName">
          <el-input
            v-model="queryParams.planName"
            placeholder="请输入预案名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="预案类型" prop="planType">
          <el-select v-model="queryParams.planType" placeholder="全部" clearable>
            <el-option
              v-for="item in planTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="事件类型" prop="eventType">
          <el-select v-model="queryParams.eventType" placeholder="全部" clearable>
            <el-option
              v-for="item in eventTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="事件级别" prop="eventLevel">
          <el-select v-model="queryParams.eventLevel" placeholder="全部" clearable>
            <el-option
              v-for="item in levelOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="全部" clearable>
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 240px"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">
            查询
          </el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"> 重置 </el-button>
        </el-form-item>
      </el-form>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
    </el-card>

    <el-card shadow="never">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['emergency:plan:add']"
          >
            新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleEdit()"
            v-hasPermi="['emergency:plan:edit']"
          >
            编辑
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['emergency:plan:remove']"
          >
            删除
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-upload2"
            size="mini"
            :disabled="multiple"
            @click="handlePublish"
            v-hasPermi="['emergency:plan:publish']"
          >
            发布
          </el-button>
        </el-col>
      </el-row>

      <el-table
        v-loading="loading"
        :data="planList"
        @selection-change="handleSelectionChange"
        border
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column prop="planNo" label="预案编号" width="160" show-overflow-tooltip />
        <el-table-column prop="planName" label="预案名称" min-width="200" show-overflow-tooltip />
        <el-table-column prop="planType" label="类型" width="100">
          <template slot-scope="scope">
            {{ renderPlanType(scope.row.planType) }}
          </template>
        </el-table-column>
        <el-table-column prop="eventType" label="事件类型" width="120">
          <template slot-scope="scope">
            {{ renderEventType(scope.row.eventType) }}
          </template>
        </el-table-column>
        <el-table-column prop="eventLevel" label="事件级别" width="110">
          <template slot-scope="scope">
            <el-tag size="mini">{{ renderEventLevel(scope.row.eventLevel) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="version" label="版本" width="80" />
        <el-table-column prop="status" label="状态" width="110">
          <template slot-scope="scope">
            <el-tag :type="statusTag(scope.row.status)">
              {{ renderStatus(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="usageCount" label="引用次数" width="100" />
        <el-table-column prop="updateTime" label="更新时间" width="180">
          <template slot-scope="scope">
            {{ parseTime(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="mini" icon="el-icon-view" @click="handleView(scope.row)">
              查看
            </el-button>
            <el-dropdown trigger="click" @command="cmd => handleAction(cmd, scope.row)">
              <span class="el-dropdown-link">
                更多操作<i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item
                  command="edit"
                  v-hasPermi="['emergency:plan:edit']"
                >
                  <i class="el-icon-edit"></i> 编辑
                </el-dropdown-item>
                <el-dropdown-item
                  command="publish"
                  v-hasPermi="['emergency:plan:publish']"
                >
                  <i class="el-icon-upload2"></i> 发布
                </el-dropdown-item>
                <el-dropdown-item
                  command="delete"
                  divided
                  v-hasPermi="['emergency:plan:remove']"
                >
                  <i class="el-icon-delete"></i> 删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

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

    <el-dialog
      :title="dialogTitle"
      :visible.sync="planDialogVisible"
      width="1000px"
      destroy-on-close
      append-to-body
      @close="handleDialogCancel"
    >
      <el-tabs v-model="planEditActiveTab">
        <!-- Basic Info Tab -->
        <el-tab-pane label="基本信息" name="basic">
          <el-form ref="planForm" :model="form" :rules="rules" label-width="100px">
            <el-form-item label="预案编号" prop="planNo">
              <el-input 
                v-model="form.planNo" 
                placeholder="请输入预案编号" 
                maxlength="50" 
                :disabled="!!form.id"
              />
            </el-form-item>
            <el-form-item label="预案名称" prop="planName">
              <el-input v-model="form.planName" placeholder="请输入预案名称" maxlength="100" />
            </el-form-item>
            <el-form-item label="预案类型" prop="planType">
              <el-select v-model="form.planType" placeholder="请选择">
                <el-option
                  v-for="item in planTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="事件类型" prop="eventType">
              <el-select v-model="form.eventType" placeholder="请选择">
                <el-option
                  v-for="item in eventTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="事件级别" prop="eventLevel">
              <el-select v-model="form.eventLevel" placeholder="请选择">
                <el-option
                  v-for="item in levelOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="描述" prop="description">
              <el-input
                type="textarea"
                :rows="3"
                v-model="form.description"
                placeholder="请输入预案描述"
              />
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <!-- Participants Tab -->
        <el-tab-pane label="执行对象" name="participants" :disabled="!form.id">
          <div class="tab-toolbar">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-plus"
              @click="openEditParticipantDialog()"
              v-hasPermi="['emergency:plan:participant:add']"
            >
              新增执行对象
            </el-button>
          </div>
          <el-table :data="editParticipants" border size="small" style="margin-top: 16px">
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column prop="displayName" label="名称" min-width="150" />
            <el-table-column prop="participantType" label="类型" width="120">
              <template slot-scope="scope">
                <el-tag size="mini">{{ scope.row.participantType === 'TEAM_MEMBER' ? '队伍成员' : '专家' }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="role" label="角色职责" min-width="160" show-overflow-tooltip />
            <el-table-column prop="sortOrder" label="顺序" width="80" />
            <el-table-column label="操作" width="180">
              <template slot-scope="scope">
                <el-button type="text" size="mini" @click="openEditParticipantDialog(scope.row)">编辑</el-button>
                <el-button
                  type="text"
                  size="mini"
                  @click="removeEditParticipant(scope.row)"
                  v-hasPermi="['emergency:plan:participant:remove']"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-empty v-if="editParticipants.length === 0" description="暂无执行对象" :image-size="80" />
        </el-tab-pane>
        
        <!-- Steps Tab -->
        <el-tab-pane label="行动项" name="steps" :disabled="!form.id">
          <div class="tab-toolbar">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-plus"
              @click="openEditStepDialog()"
              v-hasPermi="['emergency:plan:step:add']"
            >
              新增行动项
            </el-button>
          </div>
          <el-table :data="editSteps" border size="small" style="margin-top: 16px">
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column prop="stepOrder" label="顺序" width="80" />
            <el-table-column prop="stepName" label="行动项名称" min-width="150" show-overflow-tooltip />
            <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
            <el-table-column prop="estimatedDuration" label="预计耗时(分钟)" width="140" />
            <el-table-column label="资源" width="160">
              <template slot-scope="scope">
                <el-button type="text" size="mini" @click="openEditResourceManager(scope.row)">
                  管理资源 ({{ (editResourcesMap[scope.row.id] || []).length }})
                </el-button>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
              <template slot-scope="scope">
                <el-button type="text" size="mini" @click="openEditStepDialog(scope.row)">编辑</el-button>
                <el-button
                  type="text"
                  size="mini"
                  @click="removeEditStep(scope.row)"
                  v-hasPermi="['emergency:plan:step:remove']"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-empty v-if="editSteps.length === 0" description="暂无行动项" :image-size="80" />
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <!-- 移除手动创建版本按钮，因为发布时自动创建版本 -->
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="handleDialogCancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- Edit Participant Dialog -->
    <el-dialog 
      :title="editParticipantDialog.title" 
      :visible.sync="editParticipantDialog.visible" 
      width="520px" 
      append-to-body
      @close="handleEditParticipantCancel"
    >
      <el-form ref="editParticipantForm" :model="editParticipantDialog.form" :rules="participantRules" label-width="110px">
        <el-form-item label="类型" prop="participantType">
          <el-select v-model="editParticipantDialog.form.participantType" placeholder="请选择类型" @change="handleEditParticipantTypeChange">
            <el-option label="队伍成员" value="TEAM_MEMBER" />
            <el-option label="专家" value="EXPERT" />
          </el-select>
        </el-form-item>
        
        <!-- Team Member Selection -->
        <template v-if="editParticipantDialog.form.participantType === 'TEAM_MEMBER'">
          <el-form-item label="队伍" prop="referenceTeamId">
            <el-select 
              v-model="editParticipantDialog.form.referenceTeamId" 
              placeholder="请选择队伍"
              filterable
              @change="handleEditTeamChange"
              :loading="loadingTeams"
            >
              <el-option
                v-for="team in teams"
                :key="team.id"
                :label="team.teamName"
                :value="team.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="成员" prop="referenceMemberId">
            <el-select 
              v-model="editParticipantDialog.form.referenceMemberId" 
              placeholder="请选择成员"
              filterable
              :disabled="!editParticipantDialog.form.referenceTeamId"
              @change="handleEditMemberChange"
              :loading="loadingTeamMembers"
            >
              <el-option
                v-for="member in teamMembers"
                :key="member.id"
                :label="member.memberName || member.name"
                :value="member.id"
              />
            </el-select>
          </el-form-item>
        </template>
        
        <!-- Expert Selection -->
        <template v-if="editParticipantDialog.form.participantType === 'EXPERT'">
          <el-form-item label="专家" prop="referenceExpertId">
            <el-select 
              v-model="editParticipantDialog.form.referenceExpertId" 
              placeholder="请选择专家"
              filterable
              @change="handleEditExpertChange"
              :loading="loadingExperts"
            >
              <el-option
                v-for="expert in experts"
                :key="expert.id"
                :label="expert.expertName || expert.name"
                :value="expert.id"
              />
            </el-select>
          </el-form-item>
        </template>
        
        <el-form-item label="显示名称" prop="displayName">
          <el-input v-model="editParticipantDialog.form.displayName" placeholder="自动填充" :disabled="true" />
        </el-form-item>
        <el-form-item label="角色/职责">
          <el-input v-model="editParticipantDialog.form.role" placeholder="请输入角色" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="editParticipantDialog.form.sortOrder" :min="1" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="submitEditParticipant">确 定</el-button>
        <el-button @click="handleEditParticipantCancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- Edit Step Dialog -->
    <el-dialog 
      :title="editStepDialog.title" 
      :visible.sync="editStepDialog.visible" 
      width="540px" 
      append-to-body
      @close="handleEditStepCancel"
    >
      <el-form ref="editStepForm" :model="editStepDialog.form" :rules="stepRules" label-width="110px">
        <el-form-item label="行动项名称" prop="stepName">
          <el-input v-model="editStepDialog.form.stepName" placeholder="请输入行动项名称" />
        </el-form-item>
        <el-form-item label="顺序" prop="stepOrder">
          <el-input-number v-model="editStepDialog.form.stepOrder" :min="1" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input type="textarea" v-model="editStepDialog.form.description" />
        </el-form-item>
        <el-form-item label="预计耗时(分钟)">
          <el-input-number v-model="editStepDialog.form.estimatedDuration" :min="0" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="submitEditStep">确 定</el-button>
        <el-button @click="handleEditStepCancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- Edit Resource Manager Drawer -->
    <el-drawer
      title="行动项资源"
      :visible.sync="editResourceManager.visible"
      size="40%"
      append-to-body
    >
      <div class="drawer-header">
        <span>{{ editResourceManager.step && editResourceManager.step.stepName }}</span>
        <el-button type="primary" size="mini" icon="el-icon-plus" @click="openEditResourceDialog()">
          新增资源
        </el-button>
      </div>
      <el-table :data="editResourceManager.list" border size="small">
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="resourceType" label="资源类型" width="120">
          <template slot-scope="scope">
            <el-tag size="mini">{{ renderResourceType(scope.row.resourceType) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="资源名称" min-width="150" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ getResourceName(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column prop="suggestedQuantity" label="建议数量" width="120" />
        <el-table-column prop="required" label="是否必需" width="100">
          <template slot-scope="scope">
            <el-tag size="mini" :type="scope.row.required ? 'danger' : 'info'">
              {{ scope.row.required ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="usageNote" label="说明" min-width="160" show-overflow-tooltip />
        <el-table-column label="操作" width="160">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="openEditResourceDialog(scope.row)">编辑</el-button>
            <el-button type="text" size="mini" @click="removeEditResource(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-drawer>

    <!-- View Resource Manager Drawer (for detail dialog) -->
    <el-drawer
      title="行动项资源"
      :visible.sync="viewResourceManager.visible"
      size="40%"
      append-to-body
    >
      <div class="drawer-header">
        <span>{{ viewResourceManager.step && viewResourceManager.step.stepName }}</span>
      </div>
      <el-table :data="viewResourceManager.list" border size="small">
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="resourceType" label="资源类型" width="120">
          <template slot-scope="scope">
            <el-tag size="mini">{{ renderResourceType(scope.row.resourceType) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="资源名称" min-width="150" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ getResourceName(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column prop="suggestedQuantity" label="建议数量" width="120" />
        <el-table-column prop="required" label="是否必需" width="100">
          <template slot-scope="scope">
            <el-tag size="mini" :type="scope.row.required ? 'danger' : 'info'">
              {{ scope.row.required ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="usageNote" label="说明" min-width="160" show-overflow-tooltip />
      </el-table>
      <el-empty v-if="viewResourceManager.list.length === 0" description="暂无资源" :image-size="80" />
    </el-drawer>

    <!-- Edit Resource Dialog -->
    <el-dialog 
      :title="editResourceDialog.title" 
      :visible.sync="editResourceDialog.visible" 
      width="480px" 
      append-to-body
      @close="handleEditResourceCancel"
    >
      <el-form ref="editResourceForm" :model="editResourceDialog.form" :rules="resourceRules" label-width="110px">
        <el-form-item label="资源类型" prop="resourceType">
          <el-select 
            v-model="editResourceDialog.form.resourceType" 
            placeholder="请选择"
            @change="handleResourceTypeChange"
          >
            <el-option label="物资" value="material" />
            <el-option label="装备" value="equipment" />
            <el-option label="车辆" value="vehicle" />
          </el-select>
        </el-form-item>
        
        <!-- Warehouse Selection for Materials -->
        <el-form-item 
          v-if="editResourceDialog.form.resourceType === 'material'" 
          label="仓库" 
          prop="warehouseId"
        >
          <el-select 
            v-model="editResourceDialog.form.warehouseId" 
            placeholder="请选择仓库（可选）"
            filterable
            clearable
            :loading="loadingWarehouses"
            style="width: 100%"
            @change="handleWarehouseChange"
          >
            <el-option
              v-for="warehouse in warehouses"
              :key="warehouse.id"
              :label="warehouse.warehouseName"
              :value="warehouse.id"
            />
          </el-select>
        </el-form-item>
        
        <!-- Warehouse Selection for Equipment -->
        <el-form-item 
          v-if="editResourceDialog.form.resourceType === 'equipment'" 
          label="仓库" 
          prop="warehouseId"
        >
          <el-select 
            v-model="editResourceDialog.form.warehouseId" 
            placeholder="请选择仓库（可选）"
            filterable
            clearable
            :loading="loadingWarehouses"
            style="width: 100%"
            @change="handleWarehouseChange"
          >
            <el-option
              v-for="warehouse in warehouses"
              :key="warehouse.id"
              :label="warehouse.warehouseName"
              :value="warehouse.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="选择资源" prop="resourceRefId">
          <!-- Material Selection -->
          <el-select 
            v-if="editResourceDialog.form.resourceType === 'material'"
            v-model="editResourceDialog.form.resourceRefId" 
            placeholder="请选择物资"
            filterable
            clearable
            :loading="loadingMaterials"
            style="width: 100%"
          >
            <el-option
              v-for="material in filteredMaterials"
              :key="material.id"
              :label="material.materialName + (material.materialCode ? ` (${material.materialCode})` : '')"
              :value="material.id"
            />
          </el-select>
          <!-- Equipment Selection -->
          <el-select 
            v-else-if="editResourceDialog.form.resourceType === 'equipment'"
            v-model="editResourceDialog.form.resourceRefId" 
            placeholder="请选择装备"
            filterable
            clearable
            :loading="loadingEquipment"
            style="width: 100%"
          >
            <el-option
              v-for="item in filteredEquipment"
              :key="item.id"
              :label="item.equipmentName + (item.equipmentCode ? ` (${item.equipmentCode})` : '')"
              :value="item.id"
            />
          </el-select>
          <!-- Vehicle Selection -->
          <el-select 
            v-else-if="editResourceDialog.form.resourceType === 'vehicle'"
            v-model="editResourceDialog.form.resourceRefId" 
            placeholder="请选择车辆"
            filterable
            clearable
            :loading="loadingVehicles"
            style="width: 100%"
          >
            <el-option
              v-for="vehicle in vehicles"
              :key="vehicle.id"
              :label="(vehicle.vehicleName || vehicle.plateNo) + (vehicle.plateNo && vehicle.vehicleName ? ` (${vehicle.plateNo})` : '')"
              :value="vehicle.id"
            />
          </el-select>
          <el-input 
            v-else
            :value="''" 
            placeholder="请先选择资源类型"
            disabled
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="建议数量">
          <el-input-number v-model="editResourceDialog.form.suggestedQuantity" :min="1" />
        </el-form-item>
        <el-form-item label="是否必需">
          <el-switch v-model="editResourceDialog.form.required" />
        </el-form-item>
        <el-form-item label="使用说明">
          <el-input type="textarea" v-model="editResourceDialog.form.usageNote" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="submitEditResource">确 定</el-button>
        <el-button @click="handleEditResourceCancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- Version Creation Dialog -->
    <el-dialog
      title="创建版本"
      :visible.sync="versionDialog.visible"
      width="520px"
      append-to-body
      @close="handleVersionDialogCancel"
    >
      <el-form ref="versionForm" :model="versionDialog.form" :rules="versionRules" label-width="110px">
        <el-form-item label="版本号" prop="version">
          <el-input v-model="versionDialog.form.version" placeholder="例如: v1.1, v2.0" />
        </el-form-item>
        <el-form-item label="变更说明" prop="changeLog">
          <el-input
            type="textarea"
            :rows="4"
            v-model="versionDialog.form.changeLog"
            placeholder="请输入本次变更的说明"
          />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="submitVersion">确 定</el-button>
        <el-button @click="handleVersionDialogCancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- Plan Detail Dialog -->
    <el-dialog
      :visible.sync="detailDialogVisible"
      title="预案详情"
      width="1000px"
      append-to-body
      :close-on-click-modal="false"
    >
      <div v-loading="loadingDetail">
        <el-tabs v-model="detailActiveTab" v-if="currentPlan">
          <el-tab-pane label="基本信息" name="info">
            <el-descriptions :column="3" border size="small">
              <el-descriptions-item label="预案编号">{{ currentPlan.planNo || '-' }}</el-descriptions-item>
              <el-descriptions-item label="预案名称">{{ currentPlan.planName || '-' }}</el-descriptions-item>
              <el-descriptions-item label="预案类型">
                {{ renderPlanType(currentPlan.planType) }}
              </el-descriptions-item>
              <el-descriptions-item label="事件类型">
                {{ renderEventType(currentPlan.eventType) }}
              </el-descriptions-item>
              <el-descriptions-item label="事件级别">
                <el-tag size="mini">{{ renderEventLevel(currentPlan.eventLevel) }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="版本号">{{ currentPlan.version || '-' }}</el-descriptions-item>
              <el-descriptions-item label="状态">
                <el-tag :type="statusTag(currentPlan.status)" size="mini">
                  {{ renderStatus(currentPlan.status) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="是否最新版本">{{ currentPlan.isCurrent ? '是' : '否' }}</el-descriptions-item>
              <el-descriptions-item label="使用次数">{{ currentPlan.usageCount || 0 }}</el-descriptions-item>
              <el-descriptions-item label="创建时间" :span="1">
                {{ parseTime(currentPlan.createTime) }}
              </el-descriptions-item>
              <el-descriptions-item label="更新时间" :span="1">
                {{ parseTime(currentPlan.updateTime) }}
              </el-descriptions-item>
              <el-descriptions-item label="发布时间" :span="1">
                {{ currentPlan.publishTime ? parseTime(currentPlan.publishTime) : '未发布' }}
              </el-descriptions-item>
              <el-descriptions-item label="预案描述" :span="3">
                {{ currentPlan.description || '暂无描述' }}
              </el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>
          
          <el-tab-pane label="执行对象" name="participants">
            <div class="tab-toolbar" v-if="isEditMode">
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-plus"
                @click="openParticipantDialog()"
                v-hasPermi="['emergency:plan:participant:add']"
              >
                新增执行对象
              </el-button>
            </div>
            <el-table :data="planParticipants" border size="small" style="margin-top: 16px">
              <el-table-column type="index" label="序号" width="60" />
              <el-table-column prop="displayName" label="名称" min-width="150" />
              <el-table-column prop="participantType" label="类型" width="120">
                <template slot-scope="scope">
                  <el-tag size="mini">{{ scope.row.participantType === 'TEAM_MEMBER' ? '队伍成员' : '专家' }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="role" label="角色职责" min-width="160" show-overflow-tooltip />
              <el-table-column prop="sortOrder" label="顺序" width="80" />
              <el-table-column label="操作" width="180" v-if="isEditMode">
                <template slot-scope="scope">
                  <el-button type="text" size="mini" @click="openParticipantDialog(scope.row)">编辑</el-button>
                  <el-button
                    type="text"
                    size="mini"
                    @click="removeParticipant(scope.row)"
                    v-hasPermi="['emergency:plan:participant:remove']"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-empty v-if="planParticipants.length === 0" description="暂无执行对象" :image-size="80" />
          </el-tab-pane>
          
          <el-tab-pane label="行动项" name="steps">
            <div class="tab-toolbar" v-if="isEditMode">
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-plus"
                @click="openStepDialog()"
                v-hasPermi="['emergency:plan:step:add']"
              >
                新增行动项
              </el-button>
            </div>
            <div v-loading="loadingSteps">
              <el-table :data="planSteps" border size="small" style="margin-top: 16px">
                <el-table-column type="index" label="序号" width="60" />
                <el-table-column prop="stepOrder" label="顺序" width="80" />
                <el-table-column prop="stepName" label="行动项名称" min-width="150" show-overflow-tooltip />
                <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
                <el-table-column prop="estimatedDuration" label="预计耗时(分钟)" width="140" />
                <el-table-column label="资源" width="160" v-if="isEditMode">
                  <template slot-scope="scope">
                    <el-button type="text" size="mini" @click="openResourceManager(scope.row)">
                      管理资源 ({{ (planResourcesMap[scope.row.id] || []).length }})
                    </el-button>
                  </template>
                </el-table-column>
                <el-table-column label="资源数量" width="150" v-else>
                  <template slot-scope="scope">
                    <el-button 
                      type="text" 
                      size="mini" 
                      @click="openViewResourceManager(scope.row)"
                      :disabled="!planResourcesMap[scope.row.id] || planResourcesMap[scope.row.id].length === 0"
                      class="resource-count-link"
                    >
                      <i class="el-icon-view"></i>
                      <span style="margin-left: 4px;">查看资源 ({{ (planResourcesMap[scope.row.id] || []).length }})</span>
                    </el-button>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="200" v-if="isEditMode">
                  <template slot-scope="scope">
                    <el-button type="text" size="mini" @click="openStepDialog(scope.row)">编辑</el-button>
                    <el-button
                      type="text"
                      size="mini"
                      @click="removeStep(scope.row)"
                      v-hasPermi="['emergency:plan:step:remove']"
                    >
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-empty v-if="!loadingSteps && planSteps.length === 0" description="暂无行动项" :image-size="80" />
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="版本管理" name="versions">
            <!-- 移除手动创建版本按钮，因为发布时自动创建版本 -->
            <div v-loading="loadingVersions" style="margin-top: 16px">
              <el-table :data="planVersions" border size="small">
                <el-table-column type="index" label="序号" width="60" />
                <el-table-column prop="version" label="版本号" width="120" />
                <el-table-column prop="changeLog" label="变更说明" min-width="220" show-overflow-tooltip />
                <el-table-column prop="createTime" label="创建时间" width="180">
                  <template slot-scope="scope">{{ parseTime(scope.row.createTime) }}</template>
                </el-table-column>
                <el-table-column label="操作" width="160">
                  <template slot-scope="scope">
                    <el-button
                      type="text"
                      size="mini"
                      @click="handleRestoreVersion(scope.row)"
                      v-hasPermi="['emergency:plan:version:restore']"
                    >
                      恢复
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-empty v-if="!loadingVersions && planVersions.length === 0" description="暂无版本记录" :image-size="80" />
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
      <div slot="footer">
        <el-button @click="detailDialogVisible = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- Participant Dialog (for detail dialog) -->
    <el-dialog 
      :title="participantDialog.title" 
      :visible.sync="participantDialog.visible" 
      width="520px" 
      append-to-body
      @close="handleParticipantCancel"
    >
      <el-form ref="participantForm" :model="participantDialog.form" :rules="participantRules" label-width="110px">
        <el-form-item label="类型" prop="participantType">
          <el-select v-model="participantDialog.form.participantType" placeholder="请选择类型" @change="handleParticipantTypeChange">
            <el-option label="队伍成员" value="TEAM_MEMBER" />
            <el-option label="专家" value="EXPERT" />
          </el-select>
        </el-form-item>
        
        <!-- Team Member Selection -->
        <template v-if="participantDialog.form.participantType === 'TEAM_MEMBER'">
          <el-form-item label="队伍" prop="referenceTeamId">
            <el-select 
              v-model="participantDialog.form.referenceTeamId" 
              placeholder="请选择队伍"
              filterable
              @change="handleTeamChange"
              :loading="loadingTeams"
            >
              <el-option
                v-for="team in teams"
                :key="team.id"
                :label="team.teamName"
                :value="team.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="成员" prop="referenceMemberId">
            <el-select 
              v-model="participantDialog.form.referenceMemberId" 
              placeholder="请选择成员"
              filterable
              :disabled="!participantDialog.form.referenceTeamId"
              @change="handleMemberChange"
              :loading="loadingTeamMembers"
            >
              <el-option
                v-for="member in teamMembers"
                :key="member.id"
                :label="member.memberName || member.name"
                :value="member.id"
              />
            </el-select>
          </el-form-item>
        </template>
        
        <!-- Expert Selection -->
        <template v-if="participantDialog.form.participantType === 'EXPERT'">
          <el-form-item label="专家" prop="referenceExpertId">
            <el-select 
              v-model="participantDialog.form.referenceExpertId" 
              placeholder="请选择专家"
              filterable
              @change="handleExpertChange"
              :loading="loadingExperts"
            >
              <el-option
                v-for="expert in experts"
                :key="expert.id"
                :label="expert.expertName || expert.name"
                :value="expert.id"
              />
            </el-select>
          </el-form-item>
        </template>
        
        <el-form-item label="显示名称" prop="displayName">
          <el-input v-model="participantDialog.form.displayName" placeholder="自动填充" :disabled="true" />
        </el-form-item>
        <el-form-item label="角色/职责">
          <el-input v-model="participantDialog.form.role" placeholder="请输入角色" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="participantDialog.form.sortOrder" :min="1" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="submitParticipant">确 定</el-button>
        <el-button @click="handleParticipantCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listPlans,
  addPlan,
  updatePlan,
  deletePlans,
  publishPlan,
  getPlan,
  listPlanSteps,
  listStepResources,
  listPlanParticipants,
  addPlanParticipant,
  updatePlanParticipant,
  deletePlanParticipants,
  addPlanStep,
  updatePlanStep,
  deletePlanSteps,
  addStepResource,
  updateStepResource,
  deleteStepResources,
  listPlanVersions,
  createPlanVersion,
  restorePlanVersion
} from '@/api/emergency/plan'
import { listTeam, listTeamMember } from '@/api/resource/team'
import { listExpert } from '@/api/resource/expert'
import { listMaterial } from '@/api/resource/material'
import { listEquipment } from '@/api/resource/equipment'
import { listVehicle } from '@/api/resource/vehicle'
import { listWarehouse } from '@/api/resource/warehouse'
import { parseTime } from '@/utils/shuyu-utils'

export default {
  name: 'PlanCenter',
  data() {
    return {
      loading: false,
      showSearch: true,
      total: 0,
      planList: [],
      dateRange: [],
      ids: [],
      single: true,
      multiple: true,
      planDialogVisible: false,
      dialogTitle: '',
      planEditActiveTab: 'basic',
      editParticipants: [],
      editSteps: [],
      editResourcesMap: {},
      editResourceManager: {
        visible: false,
        step: null,
        list: []
      },
      editParticipantDialog: {
        visible: false,
        title: '',
        form: {}
      },
      editStepDialog: {
        visible: false,
        title: '',
        form: {}
      },
      editResourceDialog: {
        visible: false,
        title: '',
        form: {}
      },
      teams: [],
      teamMembers: [],
      experts: [],
      loadingTeams: false,
      loadingTeamMembers: false,
      loadingExperts: false,
      materials: [],
      equipment: [],
      vehicles: [],
      warehouses: [],
      loadingMaterials: false,
      loadingEquipment: false,
      loadingVehicles: false,
      loadingWarehouses: false,
      detailDialogVisible: false,
      currentPlan: null,
      loadingDetail: false,
      isEditMode: false,
      planSteps: [],
      planParticipants: [],
      planResourcesMap: {},
      planVersions: [],
      loadingSteps: false,
      loadingVersions: false,
      detailActiveTab: 'info',
      activeResourceCollapse: [],
      participantDialog: {
        visible: false,
        title: '',
        form: {}
      },
      stepDialog: {
        visible: false,
        title: '',
        form: {}
      },
      resourceManager: {
        visible: false,
        step: null,
        list: []
      },
      viewResourceManager: {
        visible: false,
        step: null,
        list: []
      },
      resourceDialog: {
        visible: false,
        title: '',
        form: {}
      },
      versionDialog: {
        visible: false,
        planId: null,
        form: {
          version: '',
          changeLog: ''
        }
      },
      participantRules: {
        participantType: [{ required: true, message: '请选择类型', trigger: 'change' }],
        referenceTeamId: [
          { 
            required: true, 
            message: '请选择队伍', 
            trigger: 'change',
            validator: (rule, value, callback) => {
              const form = this.editParticipantDialog.visible 
                ? this.editParticipantDialog.form 
                : this.participantDialog.form
              if (form.participantType === 'TEAM_MEMBER' && !value) {
                callback(new Error('请选择队伍'))
              } else {
                callback()
              }
            }
          }
        ],
        referenceMemberId: [
          { 
            required: true, 
            message: '请选择成员', 
            trigger: 'change',
            validator: (rule, value, callback) => {
              const form = this.editParticipantDialog.visible 
                ? this.editParticipantDialog.form 
                : this.participantDialog.form
              if (form.participantType === 'TEAM_MEMBER' && !value) {
                callback(new Error('请选择成员'))
              } else {
                callback()
              }
            }
          }
        ],
        referenceExpertId: [
          { 
            required: true, 
            message: '请选择专家', 
            trigger: 'change',
            validator: (rule, value, callback) => {
              const form = this.editParticipantDialog.visible 
                ? this.editParticipantDialog.form 
                : this.participantDialog.form
              if (form.participantType === 'EXPERT' && !value) {
                callback(new Error('请选择专家'))
              } else {
                callback()
              }
            }
          }
        ]
      },
      stepRules: {
        stepName: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        stepOrder: [{ required: true, message: '请输入顺序', trigger: 'change' }]
      },
      resourceRules: {
        resourceType: [{ required: true, message: '请选择资源类型', trigger: 'change' }],
        resourceRefId: [{ required: true, message: '请选择资源', trigger: 'change' }]
      },
      versionRules: {
        version: [{ required: true, message: '请输入版本号', trigger: 'blur' }],
        changeLog: [{ required: true, message: '请输入变更说明', trigger: 'blur' }]
      },
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        planName: '',
        planType: '',
        eventType: '',
        eventLevel: '',
        status: ''
      },
      form: {},
      rules: {
        planNo: [{ required: true, message: '预案编号不能为空', trigger: 'blur' }],
        planName: [{ required: true, message: '预案名称不能为空', trigger: 'blur' }],
        planType: [{ required: true, message: '请选择预案类型', trigger: 'change' }],
        eventType: [{ required: true, message: '请选择事件类型', trigger: 'change' }],
        eventLevel: [{ required: true, message: '请选择事件级别', trigger: 'change' }]
      },
      planTypeOptions: [
        { label: '总体预案', value: 'overall' },
        { label: '专项预案', value: 'special' }
      ],
      eventTypeOptions: [
        { label: '自然灾害', value: 'natural_disaster' },
        { label: '事故灾害', value: 'accident' },
        { label: '公共卫生', value: 'public_health' },
        { label: '社会安全', value: 'social_security' }
      ],
      levelOptions: [
        { label: 'Ⅰ级', value: 'I' },
        { label: 'Ⅱ级', value: 'II' },
        { label: 'Ⅲ级', value: 'III' },
        { label: 'Ⅳ级', value: 'IV' }
      ],
      statusOptions: [
        { label: '草稿', value: 'draft' },
        { label: '审批中', value: 'approving' },
        { label: '已发布', value: 'published' },
        { label: '已归档', value: 'archived' }
      ]
    }
  },
  computed: {
    // Filter materials by warehouse (if warehouse has inventory data)
    filteredMaterials() {
      if (!this.editResourceDialog.form.warehouseId) {
        return this.materials
      }
      // If materials have warehouse association, filter here
      // For now, return all materials (you may need to filter based on inventory)
      return this.materials
    },
    // Filter equipment by warehouse
    filteredEquipment() {
      if (!this.editResourceDialog.form.warehouseId) {
        return this.equipment
      }
      // Filter equipment by warehouse if equipment has warehouse_id field
      return this.equipment.filter(eq => 
        !eq.warehouseId || eq.warehouseId === this.editResourceDialog.form.warehouseId
      )
    }
  },
  created() {
    this.getList()
  },
  methods: {
    parseTime,
    renderPlanType(value) {
      const item = this.planTypeOptions.find(option => option.value === value)
      return item ? item.label : value || '-'
    },
    renderEventLevel(value) {
      const item = this.levelOptions.find(option => option.value === value)
      return item ? item.label : value || '-'
    },
    renderStatus(value) {
      const item = this.statusOptions.find(option => option.value === value)
      return item ? item.label : value || '-'
    },
    renderEventType(value) {
      const item = this.eventTypeOptions.find(option => option.value === value)
      return item ? item.label : value || '-'
    },
    renderResourceType(value) {
      const map = { material: '物资', equipment: '装备', vehicle: '车辆' }
      return map[value] || value
    },
    switchToEditMode() {
      this.isEditMode = true
    },
    statusTag(status) {
      const map = {
        draft: 'info',
        approving: 'warning',
        approved: 'success',
        published: 'success',
        rejected: 'danger',
        archived: 'default'
      }
      return map[status] || 'default'
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.dateRange = []
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        planName: '',
        planType: '',
        eventType: '',
        eventLevel: '',
        status: ''
      }
      this.getList()
    },
    getList() {
      this.loading = true
      const params = Object.assign({}, this.queryParams)
      if (this.dateRange && this.dateRange.length === 2) {
        params.beginTime = this.dateRange[0]
        params.endTime = this.dateRange[1]
      }
      listPlans(params)
        .then(res => {
          const rows = res.rows || res.data || []
          this.planList = Array.isArray(rows) ? rows : []
          this.total = res.total || this.planList.length
        })
        .catch(error => {
          console.error('获取预案列表失败:', error)
          this.$message.error(error.msg || error.message || '获取预案列表失败')
          this.planList = []
          this.total = 0
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleAdd() {
      this.resetForm()
      this.dialogTitle = '新增预案'
      this.planDialogVisible = true
    },
    async handleEdit(row) {
      console.log(row, this.ids);
      
      // 如果传入了 row，使用 row.id；否则使用选中的第一个ID
      const planId = row ? row.id : (this.ids.length > 0 ? this.ids[0] : null)
      if (!planId) {
        this.$message.warning('请选择要编辑的预案')
        return
      }
      
      this.resetForm()
      this.dialogTitle = '编辑预案'
      this.planEditActiveTab = 'basic'
      this.editParticipants = []
      this.editSteps = []
      this.editResourcesMap = {}
      this.planDialogVisible = true
      
      // 获取预案详情
      try {
        const res = await getPlan(planId)
        if (res && res.code === 200) {
          this.form = Object.assign({}, res.data || res)
        } else {
          this.$message.error(res.msg || '获取预案详情失败')
          this.planDialogVisible = false
          return
        }
      } catch (error) {
        console.error('获取预案详情失败:', error)
        this.$message.error('获取预案详情失败，请稍后重试')
        this.planDialogVisible = false
        return
      }
      
      // Load participants and steps
      this.loadEditParticipants(planId)
      this.loadEditSteps(planId)
    },
    handleView(row) {
      if (!row || !row.id) {
        this.$message.error('无效的预案数据')
        return
      }
      this.currentPlan = null
      this.planSteps = []
      this.planParticipants = []
      this.planResourcesMap = {}
      this.isEditMode = false
      this.detailDialogVisible = true
      this.detailActiveTab = 'info'
      this.loadingDetail = true
      this.loadingSteps = true
      
      // Load resources for name lookup
      if (this.materials.length === 0 && this.equipment.length === 0 && this.vehicles.length === 0) {
        this.loadMaterials()
        this.loadEquipment()
        this.loadVehicles()
      }
      
      Promise.all([
        getPlan(row.id).catch(error => {
          console.error('获取预案详情失败:', error)
          throw error
        }),
        listPlanParticipants(row.id)
          .then(res => {
            const data = res && res.code === 200 ? (res.data || res) : (res.data || res || [])
            this.planParticipants = Array.isArray(data) ? data : []
          })
          .catch(error => {
            console.error('获取执行对象失败:', error)
            this.planParticipants = []
          }),
        listPlanSteps(row.id)
          .then(res => {
            const data = res && res.code === 200 ? (res.data || res) : (res.data || res || [])
            const steps = Array.isArray(data) ? data : []
            this.planSteps = steps
            // Fetch resources for each step
            if (steps.length > 0) {
              return Promise.all(
                steps.map(step => {
                  if (!step || !step.id) return Promise.resolve()
                  return listStepResources(row.id, step.id)
                    .then(res => {
                      const resourceData = res && res.code === 200 ? (res.data || res) : (res.data || res || [])
                      this.$set(this.planResourcesMap, step.id, Array.isArray(resourceData) ? resourceData : [])
                    })
                    .catch(error => {
                      console.error(`获取行动项 ${step.id} 的资源失败:`, error)
                      this.$set(this.planResourcesMap, step.id, [])
                    })
                })
              )
            }
            return Promise.resolve()
          })
          .catch(error => {
            console.error('获取行动项失败:', error)
            this.planSteps = []
          }),
        listPlanVersions(row.id)
          .then(res => {
            const data = res && res.code === 200 ? (res.data || res) : (res.data || res || [])
            this.planVersions = Array.isArray(data) ? data : []
          })
          .catch(error => {
            console.error('获取版本列表失败:', error)
            this.planVersions = []
          })
      ])
        .then(([planRes]) => {
          if (planRes) {
            this.currentPlan = planRes.data || planRes
          } else {
            this.$message.error('获取预案详情失败')
          }
        })
        .catch(error => {
          console.error('加载预案详情失败:', error)
          this.$message.error(error.msg || error.message || '获取预案详情失败')
        })
        .finally(() => {
          this.loadingDetail = false
          this.loadingSteps = false
        })
    },
    handlePublish(row) {
      const ids = row ? [row.id] : this.ids
      if (!ids.length) {
        this.$message.warning('请选择要发布的预案')
        return
      }
      this.$modal
        .confirm('确定发布选中的预案吗？')
        .then(() => publishPlan(ids[0]))
        .then((res) => {
          if (res && res.code === 200) {
            this.$modal.msgSuccess('发布成功')
            this.getList()
          } else {
            this.$message.error(res && res.msg ? res.msg : '发布失败')
          }
        })
        .catch(error => {
          if (error !== 'cancel') {
            console.error('发布预案失败:', error)
            this.$message.error(error.msg || error.message || '发布失败')
          }
        })
    },
    handleDelete(row) {
      const ids = row ? [row.id] : this.ids
      if (!ids.length) {
        this.$message.warning('请选择要删除的预案')
        return
      }
      this.$modal
        .confirm('确认删除选中的预案吗？')
        .then(() => deletePlans(ids.join(',')))
        .then((res) => {
          if (res && res.code === 200) {
            this.$modal.msgSuccess('删除成功')
            this.getList()
          } else {
            this.$message.error(res && res.msg ? res.msg : '删除失败')
          }
        })
        .catch(error => {
          if (error !== 'cancel') {
            console.error('删除预案失败:', error)
            this.$message.error(error.msg || error.message || '删除失败')
          }
        })
    },
    handleAction(command, row) {
      switch (command) {
        case 'edit':
          this.handleEdit(row)
          break
        case 'publish':
          this.handlePublish(row)
          break
        case 'delete':
          this.handleDelete(row)
          break
        default:
          break
      }
    },
    openVersionDialog() {
      if (!this.currentPlan || !this.currentPlan.id) {
        this.$message.warning('请先选择预案')
        return
      }
      this._openVersionDialog(this.currentPlan)
    },
    openVersionDialogFromEdit() {
      if (!this.form.id) {
        this.$message.warning('请先保存预案基本信息')
        return
      }
      this._openVersionDialog(this.form)
    },
    _openVersionDialog(plan) {
      if (!plan || !plan.id) {
        this.$message.warning('请先选择预案')
        return
      }
      // Pre-fill with current version + increment suggestion
      const currentVersion = plan.version || 'v1.0'
      const versionMatch = currentVersion.match(/v?(\d+)\.(\d+)/)
      let suggestedVersion = 'v1.1'
      if (versionMatch) {
        const major = parseInt(versionMatch[1])
        const minor = parseInt(versionMatch[2])
        suggestedVersion = `v${major}.${minor + 1}`
      }
      this.versionDialog.form = {
        version: suggestedVersion,
        changeLog: ''
      }
      // Store plan ID for version creation
      this.versionDialog.planId = plan.id
      this.versionDialog.visible = true
    },
    submitVersion() {
      this.$refs.versionForm.validate(valid => {
        if (!valid) return
        const planId = this.versionDialog.planId || (this.currentPlan && this.currentPlan.id)
        if (!planId) {
          this.$message.warning('请先选择预案')
          return
        }
        const form = this.versionDialog.form
        createPlanVersion(planId, form)
          .then((res) => {
            if (res && res.code === 200) {
              this.$message.success('版本创建成功')
              this.versionDialog.visible = false
              // Reload versions if viewing detail dialog
              if (this.currentPlan && this.currentPlan.id === planId) {
                listPlanVersions(planId)
                  .then(res => {
                    const data = res && res.code === 200 ? (res.data || res) : (res.data || res || [])
                    this.planVersions = Array.isArray(data) ? data : []
                  })
                  .catch(error => {
                    console.error('获取版本列表失败:', error)
                  })
              }
            } else {
              this.$message.error(res && res.msg ? res.msg : '版本创建失败')
            }
          })
          .catch(error => {
            console.error('创建版本失败:', error)
            this.$message.error(error.msg || error.message || '版本创建失败')
          })
      })
    },
    handleVersionDialogCancel() {
      this.versionDialog.visible = false
      this.$nextTick(() => {
        if (this.$refs.versionForm) {
          this.$refs.versionForm.clearValidate()
          this.$refs.versionForm.resetFields()
        }
        this.versionDialog.form = {
          version: '',
          changeLog: ''
        }
        this.versionDialog.planId = null
      })
    },
    handleRestoreVersion(row) {
      if (!this.currentPlan || !this.currentPlan.id) {
        this.$message.warning('请先选择预案')
        return
      }
      this.$modal
        .confirm(`确定恢复到版本 ${row.version} 吗？此操作将覆盖当前预案内容。`)
        .then(() => restorePlanVersion(this.currentPlan.id, row.id))
        .then((res) => {
          if (res && res.code === 200) {
            this.$message.success('版本恢复成功')
            // Reload plan details
            this.handleView({ id: this.currentPlan.id })
          } else {
            this.$message.error(res && res.msg ? res.msg : '版本恢复失败')
          }
        })
        .catch(error => {
          if (error !== 'cancel') {
            console.error('恢复版本失败:', error)
            this.$message.error(error.msg || error.message || '版本恢复失败')
          }
        })
    },
    handleDialogCancel() {
      this.planDialogVisible = false
      this.$nextTick(() => {
        this.resetForm()
        this.editParticipants = []
        this.editSteps = []
        this.editResourcesMap = {}
        this.planEditActiveTab = 'basic'
      })
    },
    submitForm() {
      this.$refs.planForm.validate(valid => {
        if (!valid) return
        const submitFn = this.form.id
          ? updatePlan(this.form.id, this.form)
          : addPlan(this.form)
        submitFn
          .then((res) => {
            // 尝试从多个路径获取 planId
            const planId = this.form.id || 
                          (res && res.data && res.data.id) || 
                          (res && res.data && typeof res.data === 'object' && res.data.id) ||
                          (res && res.id) || 
                          null
            if (!planId) {
              this.$message.error('保存失败：未获取到预案ID')
              return
            }
            this.$modal.msgSuccess(this.form.id ? '修改成功' : '新增成功')
            
            // 如果是新创建的预案，更新 form.id（用于后续操作）
            if (!this.form.id && planId) {
              this.form.id = planId
            }
            
            // 关闭对话框并刷新列表
            this.planDialogVisible = false
            this.getList()
          })
          .catch(error => {
            console.error('保存预案失败:', error)
            this.$message.error(error.msg || error.message || '保存失败')
          })
      })
    },
    resetForm() {
      if (this.$refs.planForm) {
        this.$refs.planForm.resetFields()
      }
      this.form = {
        planNo: '',
        planName: '',
        planType: '',
        eventType: '',
        eventLevel: '',
        description: ''
      }
    },
    getOnlySelection() {
      if (this.ids.length !== 1) {
        this.$message.warning('请选择一条预案')
        return null
      }
      return this.planList.find(item => item.id === this.ids[0])
    },
    async loadEditParticipants(planId) {
      if (!planId) return
      try {
        const res = await listPlanParticipants(planId)
        if (res && res.code === 200) {
          this.editParticipants = res.data || res || []
        } else {
          this.$message.error(res.msg || '加载执行对象失败')
          this.editParticipants = []
        }
      } catch (error) {
        console.error('加载执行对象失败:', error)
        this.$message.error(error.msg || error.message || '加载执行对象失败')
        this.editParticipants = []
      }
    },
    async loadEditSteps(planId) {
      if (!planId) return Promise.resolve()
      try {
        const res = await listPlanSteps(planId)
        const steps = res && res.code === 200 ? (res.data || res) : (res.data || res || [])
        this.editSteps = Array.isArray(steps) ? steps : []
        
        // Load resources for each step
        const map = {}
        if (this.editSteps.length > 0) {
          await Promise.all(
            this.editSteps.map(async step => {
              if (!step || !step.id) return
              try {
                const res = await listStepResources(planId, step.id)
                const resources = res && res.code === 200 ? (res.data || res) : (res.data || res || [])
                map[step.id] = Array.isArray(resources) ? resources : []
              } catch (error) {
                console.error(`加载行动项 ${step.id} 的资源失败:`, error)
                map[step.id] = []
              }
            })
          )
        }
        this.editResourcesMap = map
      } catch (error) {
        console.error('加载行动项失败:', error)
        this.$message.error(error.msg || error.message || '加载行动项失败')
        this.editSteps = []
        this.editResourcesMap = {}
      }
    },
    async loadTeams() {
      this.loadingTeams = true
      try {
        const res = await listTeam({ pageNum: 1, pageSize: 1000 })
        this.teams = res.rows || res.data || []
      } catch (error) {
        this.$message.error('加载队伍列表失败')
      } finally {
        this.loadingTeams = false
      }
    },
    async loadTeamMembers(teamId) {
      if (!teamId) {
        this.teamMembers = []
        return
      }
      if (this.loadingTeamMembers) return // Prevent duplicate requests
      this.loadingTeamMembers = true
      try {
        const res = await listTeamMember(teamId, { pageNum: 1, pageSize: 1000 })
        if (res && res.code === 200) {
          this.teamMembers = res.rows || res.data || []
        } else {
          this.$message.error(res.msg || '加载成员列表失败')
          this.teamMembers = []
        }
      } catch (error) {
        console.error('加载成员列表失败:', error)
        this.$message.error(error.msg || error.message || '加载成员列表失败')
        this.teamMembers = []
      } finally {
        this.loadingTeamMembers = false
      }
    },
    async loadExperts() {
      if (this.loadingExperts) return // Prevent duplicate requests
      this.loadingExperts = true
      try {
        const res = await listExpert({ pageNum: 1, pageSize: 1000 })
        if (res && res.code === 200) {
          this.experts = res.rows || res.data || []
        } else {
          this.$message.error(res.msg || '加载专家列表失败')
          this.experts = []
        }
      } catch (error) {
        console.error('加载专家列表失败:', error)
        this.$message.error(error.msg || error.message || '加载专家列表失败')
        this.experts = []
      } finally {
        this.loadingExperts = false
      }
    },
    handleEditParticipantTypeChange() {
      // Reset selections when type changes
      this.editParticipantDialog.form.referenceTeamId = null
      this.editParticipantDialog.form.referenceMemberId = null
      this.editParticipantDialog.form.referenceExpertId = null
      this.editParticipantDialog.form.displayName = ''
      this.teamMembers = []
    },
    handleEditTeamChange() {
      const teamId = this.editParticipantDialog.form.referenceTeamId
      this.editParticipantDialog.form.referenceMemberId = null
      this.editParticipantDialog.form.displayName = ''
      this.loadTeamMembers(teamId)
    },
    handleEditMemberChange() {
      const memberId = this.editParticipantDialog.form.referenceMemberId
      if (memberId) {
        const member = this.teamMembers.find(m => m.id === memberId)
        if (member) {
          this.editParticipantDialog.form.displayName = member.memberName || member.name || ''
        }
      }
    },
    handleEditExpertChange() {
      const expertId = this.editParticipantDialog.form.referenceExpertId
      if (expertId) {
        const expert = this.experts.find(e => e.id === expertId)
        if (expert) {
          this.editParticipantDialog.form.displayName = expert.expertName || expert.name || ''
        }
      }
    },
    openEditParticipantDialog(row) {
      this.editParticipantDialog.visible = true
      this.editParticipantDialog.title = row ? '编辑执行对象' : '新增执行对象'
      
      // Load teams and experts when opening dialog
      this.loadTeams()
      this.loadExperts()
      
      if (row) {
        this.editParticipantDialog.form = Object.assign({}, row)
        // If editing and has teamId, load members
        if (row.referenceTeamId) {
          this.loadTeamMembers(row.referenceTeamId)
        }
      } else {
        this.editParticipantDialog.form = {
          displayName: '',
          participantType: '',
          role: '',
          sortOrder: this.editParticipants.length + 1,
          referenceTeamId: null,
          referenceMemberId: null,
          referenceExpertId: null
        }
      }
    },
    handleEditParticipantCancel() {
      // Close dialog first to prevent validators from running
      this.editParticipantDialog.visible = false
      // Reset form after dialog closes to avoid triggering change handlers
      this.$nextTick(() => {
        // Clear validation errors
        if (this.$refs.editParticipantForm) {
          this.$refs.editParticipantForm.clearValidate()
          this.$refs.editParticipantForm.resetFields()
        }
        // Reset form data
        this.editParticipantDialog.form = {
          displayName: '',
          participantType: '',
          role: '',
          sortOrder: this.editParticipants.length + 1,
          referenceTeamId: null,
          referenceMemberId: null,
          referenceExpertId: null
        }
        // Clear loaded data
        this.teamMembers = []
      })
    },
    submitEditParticipant() {
      this.$refs.editParticipantForm.validate(valid => {
        if (!valid) return
        const form = this.editParticipantDialog.form
        const planId = this.form.id
        if (!planId) {
          this.$message.warning('请先保存预案基本信息')
          return
        }
        const req = form.id
          ? updatePlanParticipant(planId, form.id, form)
          : addPlanParticipant(planId, form)
        req.then((res) => {
          if (res && res.code === 200) {
            this.$message.success(form.id ? '更新成功' : '新增成功')
            this.editParticipantDialog.visible = false
            this.loadEditParticipants(planId)
          } else {
            this.$message.error(res.msg || (form.id ? '更新失败' : '新增失败'))
          }
        }).catch(error => {
          console.error('保存执行对象失败:', error)
          this.$message.error(error.msg || error.message || (form.id ? '更新失败' : '新增失败'))
        })
      })
    },
    removeEditParticipant(row) {
      const planId = this.form.id
      if (!planId) {
        this.$message.warning('预案ID不存在')
        return
      }
      if (!row || !row.id) {
        this.$message.warning('执行对象ID不存在')
        return
      }
      this.$confirm('确认删除该执行对象吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => deletePlanParticipants(planId, row.id))
        .then((res) => {
          if (res && res.code === 200) {
            this.$message.success('删除成功')
            this.loadEditParticipants(planId)
          } else {
            this.$message.error(res && res.msg ? res.msg : '删除失败')
          }
        })
        .catch(error => {
          if (error !== 'cancel') {
            console.error('删除执行对象失败:', error)
            this.$message.error(error.msg || error.message || '删除失败')
          }
        })
    },
    openEditStepDialog(row) {
      this.editStepDialog.visible = true
      this.editStepDialog.title = row ? '编辑行动项' : '新增行动项'
      this.editStepDialog.form = row
        ? Object.assign({}, row)
        : {
            stepName: '',
            stepOrder: this.editSteps.length + 1,
            description: '',
            estimatedDuration: 0
          }
      // Clear validation when opening
      this.$nextTick(() => {
        if (this.$refs.editStepForm) {
          this.$refs.editStepForm.clearValidate()
        }
      })
    },
    handleEditStepCancel() {
      this.editStepDialog.visible = false
      this.$nextTick(() => {
        if (this.$refs.editStepForm) {
          this.$refs.editStepForm.clearValidate()
          this.$refs.editStepForm.resetFields()
        }
        this.editStepDialog.form = {
          stepName: '',
          stepOrder: this.editSteps.length + 1,
          description: '',
          estimatedDuration: 0
        }
      })
    },
    submitEditStep() {
      this.$refs.editStepForm.validate(valid => {
        if (!valid) return
        const form = this.editStepDialog.form
        const planId = this.form.id
        if (!planId) {
          this.$message.warning('请先保存预案基本信息')
          return
        }
        const req = form.id
          ? updatePlanStep(planId, form.id, form)
          : addPlanStep(planId, form)
        req.then((res) => {
          if (res && res.code === 200) {
            this.$message.success(form.id ? '更新成功' : '新增成功')
            this.editStepDialog.visible = false
            this.loadEditSteps(planId)
          } else {
            this.$message.error(res.msg || (form.id ? '更新失败' : '新增失败'))
          }
        }).catch(error => {
          console.error('保存行动项失败:', error)
          this.$message.error(error.msg || error.message || (form.id ? '更新失败' : '新增失败'))
        })
      })
    },
    removeEditStep(row) {
      const planId = this.form.id
      if (!planId) {
        this.$message.warning('预案ID不存在')
        return
      }
      if (!row || !row.id) {
        this.$message.warning('行动项ID不存在')
        return
      }
      this.$confirm('确认删除该行动项吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => deletePlanSteps(planId, row.id))
        .then((res) => {
          if (res && res.code === 200) {
            this.$message.success('删除成功')
            this.loadEditSteps(planId)
          } else {
            this.$message.error(res && res.msg ? res.msg : '删除失败')
          }
        })
        .catch(error => {
          if (error !== 'cancel') {
            console.error('删除行动项失败:', error)
            this.$message.error(error.msg || error.message || '删除失败')
          }
        })
    },
    openEditResourceManager(step) {
      this.editResourceManager.visible = true
      this.editResourceManager.step = step
      this.editResourceManager.list = this.editResourcesMap[step.id] || []
      // Load resources if not already loaded
      if (this.materials.length === 0 && this.equipment.length === 0 && this.vehicles.length === 0) {
        this.loadMaterials()
        this.loadEquipment()
        this.loadVehicles()
      }
    },
    // Open view-only resource manager (for detail dialog)
    openViewResourceManager(step) {
      this.viewResourceManager.visible = true
      this.viewResourceManager.step = step
      this.viewResourceManager.list = this.planResourcesMap[step.id] || []
      // Load resources if not already loaded for name lookup
      if (this.materials.length === 0 && this.equipment.length === 0 && this.vehicles.length === 0) {
        this.loadMaterials()
        this.loadEquipment()
        this.loadVehicles()
      }
    },
    openEditResourceDialog(row) {
      this.editResourceDialog.visible = true
      this.editResourceDialog.title = row ? '编辑资源' : '新增资源'
      this.editResourceDialog.form = row
        ? Object.assign({}, row)
        : {
            resourceType: '',
            warehouseId: null,
            resourceRefId: null,
            suggestedQuantity: 1,
            required: false,
            usageNote: ''
          }
      
      // Load resources based on type when opening dialog
      if (this.editResourceDialog.form.resourceType) {
        this.handleResourceTypeChange()
      } else {
        // Load warehouses if not set yet
        this.loadWarehouses()
      }
      
      // Clear validation when opening
      this.$nextTick(() => {
        if (this.$refs.editResourceForm) {
          this.$refs.editResourceForm.clearValidate()
        }
      })
    },
    handleEditResourceCancel() {
      this.editResourceDialog.visible = false
      this.$nextTick(() => {
        if (this.$refs.editResourceForm) {
          this.$refs.editResourceForm.clearValidate()
          this.$refs.editResourceForm.resetFields()
        }
        this.editResourceDialog.form = {
          resourceType: '',
          warehouseId: null,
          resourceRefId: null,
          suggestedQuantity: 1,
          required: false,
          usageNote: ''
        }
      })
    },
    submitEditResource() {
      this.$refs.editResourceForm.validate(valid => {
        if (!valid) return
        const stepId = this.editResourceManager.step && this.editResourceManager.step.id
        if (!stepId) {
          this.$message.error('行动项ID不存在')
          return
        }
        const form = this.editResourceDialog.form
        const planId = this.form.id
        if (!planId) {
          this.$message.warning('请先保存预案基本信息')
          return
        }
        const req = form.id
          ? updateStepResource(planId, stepId, form.id, form)
          : addStepResource(planId, stepId, form)
        req.then((res) => {
          if (res && res.code === 200) {
            this.$message.success(form.id ? '更新成功' : '新增成功')
            this.editResourceDialog.visible = false
            this.loadEditSteps(planId).then(() => {
              this.editResourceManager.list = this.editResourcesMap[stepId] || []
            })
          } else {
            this.$message.error(res.msg || (form.id ? '更新失败' : '新增失败'))
          }
        }).catch(error => {
          console.error('保存资源失败:', error)
          this.$message.error(error.msg || error.message || (form.id ? '更新失败' : '新增失败'))
        })
      })
    },
    removeEditResource(row) {
      const stepId = this.editResourceManager.step && this.editResourceManager.step.id
      if (!stepId) {
        this.$message.warning('行动项ID不存在')
        return
      }
      const planId = this.form.id
      if (!planId) {
        this.$message.warning('预案ID不存在')
        return
      }
      if (!row || !row.id) {
        this.$message.warning('资源ID不存在')
        return
      }
      this.$confirm('确认删除该资源吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => deleteStepResources(planId, stepId, row.id))
        .then((res) => {
          if (res && res.code === 200) {
            this.$message.success('删除成功')
            this.loadEditSteps(planId).then(() => {
              this.editResourceManager.list = this.editResourcesMap[stepId] || []
            })
          } else {
            this.$message.error(res && res.msg ? res.msg : '删除失败')
          }
        })
        .catch(error => {
          if (error !== 'cancel') {
            console.error('删除资源失败:', error)
            this.$message.error(error.msg || error.message || '删除失败')
          }
        })
    },
    async fetchParticipants() {
      if (!this.currentPlan || !this.currentPlan.id) return
      try {
        const res = await listPlanParticipants(this.currentPlan.id)
        if (res && res.code === 200) {
          this.planParticipants = res.data || res || []
        } else {
          this.$message.error(res.msg || '加载执行对象失败')
          this.planParticipants = []
        }
      } catch (error) {
        console.error('加载执行对象失败:', error)
        this.$message.error(error.msg || error.message || '加载执行对象失败')
        this.planParticipants = []
      }
    },
    handleParticipantTypeChange() {
      // Reset selections when type changes
      this.participantDialog.form.referenceTeamId = null
      this.participantDialog.form.referenceMemberId = null
      this.participantDialog.form.referenceExpertId = null
      this.participantDialog.form.displayName = ''
      this.teamMembers = []
    },
    handleTeamChange() {
      const teamId = this.participantDialog.form.referenceTeamId
      this.participantDialog.form.referenceMemberId = null
      this.participantDialog.form.displayName = ''
      this.loadTeamMembers(teamId)
    },
    handleMemberChange() {
      const memberId = this.participantDialog.form.referenceMemberId
      if (memberId) {
        const member = this.teamMembers.find(m => m.id === memberId)
        if (member) {
          this.participantDialog.form.displayName = member.memberName || member.name || ''
        }
      }
    },
    handleExpertChange() {
      const expertId = this.participantDialog.form.referenceExpertId
      if (expertId) {
        const expert = this.experts.find(e => e.id === expertId)
        if (expert) {
          this.participantDialog.form.displayName = expert.expertName || expert.name || ''
        }
      }
    },
    openParticipantDialog(row) {
      this.participantDialog.visible = true
      this.participantDialog.title = row ? '编辑执行对象' : '新增执行对象'
      
      // Load teams and experts when opening dialog
      this.loadTeams()
      this.loadExperts()
      
      if (row) {
        this.participantDialog.form = Object.assign({}, row)
        // If editing and has teamId, load members
        if (row.referenceTeamId) {
          this.loadTeamMembers(row.referenceTeamId)
        }
      } else {
        this.participantDialog.form = {
          displayName: '',
          participantType: '',
          role: '',
          sortOrder: this.planParticipants.length + 1,
          referenceTeamId: null,
          referenceMemberId: null,
          referenceExpertId: null
        }
      }
    },
    handleParticipantCancel() {
      // Close dialog first to prevent validators from running
      this.participantDialog.visible = false
      // Reset form after dialog closes to avoid triggering change handlers
      this.$nextTick(() => {
        // Clear validation errors
        if (this.$refs.participantForm) {
          this.$refs.participantForm.clearValidate()
          this.$refs.participantForm.resetFields()
        }
        // Reset form data
        this.participantDialog.form = {
          displayName: '',
          participantType: '',
          role: '',
          sortOrder: this.planParticipants.length + 1,
          referenceTeamId: null,
          referenceMemberId: null,
          referenceExpertId: null
        }
        // Clear loaded data
        this.teamMembers = []
      })
    },
    submitParticipant() {
      this.$refs.participantForm.validate(valid => {
        if (!valid) return
        const form = this.participantDialog.form
        const planId = this.currentPlan.id
        if (!planId) {
          this.$message.error('预案ID不存在')
          return
        }
        const req = form.id
          ? updatePlanParticipant(planId, form.id, form)
          : addPlanParticipant(planId, form)
        req.then((res) => {
          if (res && res.code === 200) {
            this.$message.success(form.id ? '更新成功' : '新增成功')
            this.participantDialog.visible = false
            this.fetchParticipants()
          } else {
            this.$message.error(res.msg || (form.id ? '更新失败' : '新增失败'))
          }
        }).catch(error => {
          console.error('保存执行对象失败:', error)
          this.$message.error(error.msg || error.message || (form.id ? '更新失败' : '新增失败'))
        })
      })
    },
    // Handle resource type change
    handleResourceTypeChange() {
      // Reset selections when type changes
      this.editResourceDialog.form.warehouseId = null
      this.editResourceDialog.form.resourceRefId = null
      // Load the appropriate resource list
      if (this.editResourceDialog.form.resourceType === 'material') {
        this.loadMaterials()
        this.loadWarehouses()
      } else if (this.editResourceDialog.form.resourceType === 'equipment') {
        this.loadEquipment()
        this.loadWarehouses()
      } else if (this.editResourceDialog.form.resourceType === 'vehicle') {
        this.loadVehicles()
      }
    },
    // Load warehouses
    async loadWarehouses() {
      if (this.loadingWarehouses) return
      this.loadingWarehouses = true
      try {
        const res = await listWarehouse({ pageNum: 1, pageSize: 1000 })
        this.warehouses = res.rows || res.data || []
      } catch (error) {
        console.error('加载仓库列表失败:', error)
        this.$message.error('加载仓库列表失败')
        this.warehouses = []
      } finally {
        this.loadingWarehouses = false
      }
    },
    // Handle warehouse change
    handleWarehouseChange() {
      // Reset resource selection when warehouse changes
      this.editResourceDialog.form.resourceRefId = null
      // Materials/equipment are filtered by computed properties
    },
    // Get resource name by type and ID
    getResourceName(resource) {
      if (!resource || !resource.resourceRefId) {
        return '-'
      }
      
      const resourceId = resource.resourceRefId
      const resourceType = resource.resourceType
      
      if (resourceType === 'material') {
        const material = this.materials.find(m => 
          m.id === resourceId || 
          String(m.id) === String(resourceId) ||
          Number(m.id) === Number(resourceId)
        )
        if (material) {
          return material.materialName + (material.materialCode ? ` (${material.materialCode})` : '')
        }
      } else if (resourceType === 'equipment') {
        const equipment = this.equipment.find(e => 
          e.id === resourceId || 
          String(e.id) === String(resourceId) ||
          Number(e.id) === Number(resourceId)
        )
        if (equipment) {
          return equipment.equipmentName + (equipment.equipmentCode ? ` (${equipment.equipmentCode})` : '')
        }
      } else if (resourceType === 'vehicle') {
        const vehicle = this.vehicles.find(v => 
          v.id === resourceId || 
          String(v.id) === String(resourceId) ||
          Number(v.id) === Number(resourceId)
        )
        if (vehicle) {
          return (vehicle.vehicleName || vehicle.plateNo) + (vehicle.plateNo && vehicle.vehicleName ? ` (${vehicle.plateNo})` : '')
        }
      }
      
      // Fallback to ID if not found
      return `资源 #${resourceId}`
    },
    // Load materials
    async loadMaterials() {
      if (this.loadingMaterials) return
      this.loadingMaterials = true
      try {
        const res = await listMaterial({ pageNum: 1, pageSize: 1000 })
        this.materials = res.rows || res.data || []
      } catch (error) {
        console.error('加载物资列表失败:', error)
        this.$message.error('加载物资列表失败')
        this.materials = []
      } finally {
        this.loadingMaterials = false
      }
    },
    // Load equipment
    async loadEquipment() {
      if (this.loadingEquipment) return
      this.loadingEquipment = true
      try {
        const res = await listEquipment({ pageNum: 1, pageSize: 1000 })
        this.equipment = res.rows || res.data || []
      } catch (error) {
        console.error('加载装备列表失败:', error)
        this.$message.error('加载装备列表失败')
        this.equipment = []
      } finally {
        this.loadingEquipment = false
      }
    },
    // Load vehicles
    async loadVehicles() {
      if (this.loadingVehicles) return
      this.loadingVehicles = true
      try {
        const res = await listVehicle({ pageNum: 1, pageSize: 1000 })
        this.vehicles = res.rows || res.data || []
      } catch (error) {
        console.error('加载车辆列表失败:', error)
        this.$message.error('加载车辆列表失败')
        this.vehicles = []
      } finally {
        this.loadingVehicles = false
      }
    },
    removeParticipant(row) {
      if (!this.currentPlan || !this.currentPlan.id) {
        this.$message.warning('预案ID不存在')
        return
      }
      if (!row || !row.id) {
        this.$message.warning('执行对象ID不存在')
        return
      }
      this.$confirm('确认删除该执行对象吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => deletePlanParticipants(this.currentPlan.id, row.id))
        .then((res) => {
          if (res && res.code === 200) {
            this.$message.success('删除成功')
            this.fetchParticipants()
          } else {
            this.$message.error(res && res.msg ? res.msg : '删除失败')
          }
        })
        .catch(error => {
          if (error !== 'cancel') {
            console.error('删除执行对象失败:', error)
            this.$message.error(error.msg || error.message || '删除失败')
          }
        })
    }
  }
}
</script>

<style scoped>
.filter-card {
  margin-bottom: 16px;
}

.tab-toolbar {
  margin-bottom: 12px;
  text-align: right;
}

.drawer-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.plan-center .mb8 {
  margin-bottom: 12px;
}

.el-dropdown-link {
  cursor: pointer;
  color: #409EFF;
  font-size: 12px;
  margin-left: 8px;
}
.el-dropdown-link:hover {
  color: #66b1ff;
}

/* Add padding to drawer body */
::v-deep .el-drawer__body {
  padding: 20px;
}

/* Resource count link styling */
.resource-count-link {
  color: #409EFF;
  padding: 0;
}
.resource-count-link:hover {
  color: #66b1ff;
}
.resource-count-link:disabled {
  color: #c0c4cc;
  cursor: not-allowed;
}
.resource-count-link:disabled:hover {
  color: #c0c4cc;
}
</style>