<template>
  <GiPageLayout>
    <div class="personnel-organization-container">
      <!-- 流程导航 -->
      <div class="process-flow">
        <div class="flow-step" :class="{ active: currentStep >= 1 }">
          <div class="step-icon">
            <icon-apps />
          </div>
          <div class="step-text">项目选择</div>
        </div>
        <div class="flow-arrow">→</div>
        <div class="flow-step" :class="{ active: currentStep >= 2 }">
          <div class="step-icon">
            <icon-user-group />
          </div>
          <div class="step-text">工作组创建</div>
        </div>
        <div class="flow-arrow">→</div>
        <div class="flow-step" :class="{ active: currentStep >= 3 }">
          <div class="step-icon">
            <icon-user-add />
          </div>
          <div class="step-text">工人分配</div>
        </div>
      </div>

      <!-- 步骤1: 项目选择器 -->
      <div v-if="currentStep === 1" class="step-content">
        <a-card class="project-selection-card" :bordered="false">
          <template #title>
            <div class="card-title">
              <icon-folder />
              <span>选择项目</span>
            </div>
          </template>
          
          <div class="project-grid">
            <div 
              v-for="project in projectList" 
              :key="project.projectId" 
              class="project-card"
              :class="{ selected: selectedProject?.projectId === project.projectId }"
              @click="selectProject(project)"
            >
              <div class="project-header">
                <div class="project-icon">
                  <icon-apps />
                </div>
                <div class="project-status">
                  <a-tag :color="getStatusColor(project.status)" size="small">
                    {{ project.statusLabel }}
                  </a-tag>
                </div>
              </div>
              
              <div class="project-info">
                <h3 class="project-name">{{ project.projectName }}</h3>
                <p class="project-code">{{ project.projectCode }}</p>
                <p class="project-farm">{{ project.farmName }}</p>
              </div>
              
              <!-- 显示项目下的工作组信息 -->
              <div class="project-work-groups" v-if="project.workGroups && project.workGroups.length > 0">
                <div class="work-groups-header">
                  <icon-user-group />
                  <span>工作组 ({{ project.workGroups.length }})</span>
                </div>
                <div class="work-groups-list">
                  <div 
                    v-for="workGroup in project.workGroups.slice(0, 3)" 
                    :key="workGroup.id"
                    class="work-group-preview"
                  >
                    <span class="work-group-name">{{ workGroup.name }}</span>
                    <span class="work-group-count">{{ workGroup.memberCount }}/{{ workGroup.requiredCount }}</span>
                  </div>
                  <div v-if="project.workGroups.length > 3" class="more-work-groups">
                    +{{ project.workGroups.length - 3 }} 个工作组
                  </div>
                </div>
              </div>
              
              <div class="project-actions">
                <a-button type="primary" @click.stop="enterWorkGroupCreation(project)">
                  <template #icon><icon-arrow-right /></template>
                  进入工作组创建
                </a-button>
                <a-button 
                  v-if="project.workGroups && project.workGroups.length > 0"
                  @click.stop="viewProjectWorkGroups(project)"
                  style="margin-top: 8px;"
                >
                  <template #icon><icon-eye /></template>
                  查看工作组详情
                </a-button>
              </div>
            </div>
          </div>
        </a-card>
      </div>

      <!-- 步骤2: 工作组创建表单 -->
      <div v-if="currentStep === 2" class="step-content">
        <a-card class="work-group-form-card" :bordered="false">
          <template #title>
            <div class="card-title">
              <icon-user-group />
              <span>创建工作组</span>
              <span class="project-info-text">- {{ selectedProject?.projectName }}</span>
            </div>
          </template>
          
          <a-form :model="workGroupForm" layout="vertical" class="work-group-form">
            <a-row :gutter="24">
              <a-col :span="12">
                <a-form-item label="工作组名称" required>
                  <a-input v-model="workGroupForm.name" placeholder="请输入工作组名称" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="关联项目ID" required>
                  <a-input v-model="workGroupForm.projectId" :value="selectedProject?.projectId" disabled />
                </a-form-item>
              </a-col>
            </a-row>
            
            <a-form-item label="工作组描述">
              <a-textarea 
                v-model="workGroupForm.description" 
                placeholder="请输入工作组描述"
                :rows="3"
              />
            </a-form-item>
            
            <a-form-item label="工种分组">
              <div class="work-type-groups">
                <div 
                  v-for="(group, index) in workGroupForm.workTypeGroups" 
                  :key="index"
                  class="work-type-group-item"
                >
                  <a-row :gutter="16">
                    <a-col :span="8">
                      <a-input 
                        v-model="group.name" 
                        placeholder="工种名称"
                        :prefix="`${index + 1}.`"
                      />
                    </a-col>
                    <a-col :span="8">
                      <a-input-number 
                        v-model="group.requiredCount" 
                        :min="1" 
                        :max="100"
                        placeholder="需求人数"
                        style="width: 100%"
                      />
                    </a-col>
                    <a-col :span="6">
                      <a-select 
                        v-model="group.priority" 
                        placeholder="优先级"
                        style="width: 100%"
                      >
                        <a-option value="HIGH">高</a-option>
                        <a-option value="MEDIUM">中</a-option>
                        <a-option value="LOW">低</a-option>
                      </a-select>
                    </a-col>
                    <a-col :span="2">
                      <a-button 
                        type="text" 
                        status="danger" 
                        @click="removeWorkTypeGroup(index)"
                        :disabled="workGroupForm.workTypeGroups.length === 1"
                      >
                        <template #icon><icon-delete /></template>
                      </a-button>
                    </a-col>
                  </a-row>
                </div>
                
                <div class="add-work-type-group">
                  <a-button type="dashed" @click="addWorkTypeGroup" block>
                    <template #icon><icon-plus /></template>
                    添加工种分组
                  </a-button>
                </div>
              </div>
            </a-form-item>
            
            <div class="form-actions">
              <a-button @click="goBackToStep1">
                <template #icon><icon-arrow-left /></template>
                返回项目选择
              </a-button>
              <a-button type="primary" @click="createWorkGroup">
                <template #icon><icon-check /></template>
                创建工作组并进入分配
              </a-button>
            </div>
          </a-form>
        </a-card>
      </div>

      <!-- 步骤3: 工人分配页 -->
      <div v-if="currentStep === 3" class="step-content">
        <div class="worker-assignment-layout">
          <!-- 左侧筛选栏 -->
          <div class="filter-sidebar">
            <a-card class="filter-card" :bordered="false">
              <template #title>
                <div class="card-title">
                  <icon-filter />
                  <span>筛选条件</span>
                </div>
              </template>
              
              <div class="filter-content">
                <a-form layout="vertical">
                  <a-form-item label="工种筛选">
                    <a-checkbox-group v-model="filterForm.workTypes" @change="handleFilterChange">
                      <a-checkbox value="TOWER_CLIMB">塔上登高作业</a-checkbox>
                      <a-checkbox value="GROUND_CREW">地勤人员</a-checkbox>
                      <a-checkbox value="DRIVER">司机</a-checkbox>
                      <a-checkbox value="DRONE_PILOT">无人机飞手</a-checkbox>
                      <a-checkbox value="BASKET_REPAIR">吊篮维修工</a-checkbox>
                      <a-checkbox value="ELECTRICAL_ENG">电气工程师</a-checkbox>
                      <a-checkbox value="MECHANICAL_ENG">机械工程师</a-checkbox>
                      <a-checkbox value="SAFETY_MANAGER">安全管理员</a-checkbox>
                    </a-checkbox-group>
                  </a-form-item>
                  
                  <a-form-item label="证书关键词">
                    <a-input-search 
                      v-model="filterForm.certificateKeyword"
                      placeholder="搜索证书名称"
                      @search="handleFilterChange"
                      @clear="handleFilterChange"
                    />
                  </a-form-item>
                  
                  <a-form-item>
                    <a-button type="primary" @click="handleFilterChange" block>
                      <template #icon><icon-search /></template>
                      应用筛选
                    </a-button>
                  </a-form-item>
                  
                  <a-form-item>
                    <a-button @click="resetFilter" block>
                      <template #icon><icon-refresh /></template>
                      重置筛选
                    </a-button>
                  </a-form-item>
                </a-form>
              </div>
            </a-card>
          </div>
          
          <!-- 中间工人表格 -->
          <div class="worker-table-section">
            <a-card class="worker-table-card" :bordered="false">
              <template #title>
                <div class="card-title">
                  <icon-user-group />
                  <span>工人列表</span>
                  <span class="worker-count">({{ filteredWorkers.length }}人)</span>
                </div>
              </template>
              
              <div class="worker-table">
                <div 
                  v-for="worker in filteredWorkers" 
                  :key="worker.id"
                  class="worker-item"
                  draggable="true"
                  @dragstart="handleDragStart($event, worker)"
                  @dragend="handleDragEnd"
                >
                  <div class="worker-avatar">
                    <a-avatar :src="worker.avatar" :size="48">
                      {{ worker.name.charAt(0) }}
                    </a-avatar>
                  </div>
                  
                  <div class="worker-info">
                    <div class="worker-name">
                      <h4>{{ worker.name }}</h4>
                      <a-tag :color="getWorkerStatusColor(worker.status)" size="small">
                        {{ getWorkerStatusText(worker.status) }}
                      </a-tag>
                    </div>
                    
                    <div class="worker-details">
                      <span class="phone">{{ worker.phone }}</span>
                      <span class="experience">{{ worker.experience }}年经验</span>
                      <span class="rating">
                        <icon-star-fill style="color: #fadb14;" />
                        {{ worker.rating }}
                      </span>
                    </div>
                    
                    <div class="worker-skills">
                      <a-tag 
                        v-for="workType in worker.workTypes" 
                        :key="workType"
                        size="small"
                        color="blue"
                      >
                        {{ workType }}
                      </a-tag>
                    </div>
                  </div>
                  
                  <div class="worker-certificates">
                    <div class="certificates-header">
                      <span class="label">证书：</span>
                      <a-button 
                        type="text" 
                        size="small" 
                        @click="viewWorkerCertificates(worker)"
                      >
                        查看 ({{ worker.certifications.length }})
                      </a-button>
                    </div>
                    <div class="certificates-preview">
                      <a-tag 
                        v-for="cert in worker.certifications.slice(0, 3)" 
                        :key="cert.id"
                        :color="getCertificateStatusColor(cert.status)"
                        size="small"
                      >
                        {{ cert.name }}
                      </a-tag>
                      <span v-if="worker.certifications.length > 3" class="more-certs">
                        +{{ worker.certifications.length - 3 }}
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            </a-card>
          </div>

          <!-- 右侧工种分组栏 -->
          <div class="work-groups-sidebar">
            <a-card class="work-groups-card" :bordered="false">
              <template #title>
                <div class="card-title">
                  <icon-user-group />
                  <span>工种分组</span>
                </div>
              </template>
              
              <div class="work-groups-content">
                <div 
                  v-for="group in workGroupForm.workTypeGroups" 
                  :key="group.name"
                  class="work-group-drop-zone"
                  @dragover="handleDragOver"
                  @drop="handleDrop($event, group)"
                >
                  <div class="work-group-header">
                    <h4>{{ group.name }}</h4>
                    <div class="work-group-stats">
                      <span class="assigned">{{ getAssignedCount(group.name) }}</span>
                      <span class="separator">/</span>
                      <span class="required">{{ group.requiredCount }}</span>
                    </div>
                  </div>
                  
                  <div class="work-group-members">
                    <div 
                      v-for="member in getGroupMembers(group.name)" 
                      :key="member.id"
                      class="group-member"
                    >
                      <a-avatar :src="member.avatar" :size="32">
                        {{ member.name.charAt(0) }}
                      </a-avatar>
                      <span class="member-name">{{ member.name }}</span>
                      <a-button 
                        type="text" 
                        size="small" 
                        status="danger"
                        @click="removeFromGroup(member, group.name)"
                      >
                        <template #icon><icon-close /></template>
                      </a-button>
                    </div>
                    
                    <div v-if="getAssignedCount(group.name) < group.requiredCount" class="drop-hint">
                      拖拽工人到此处
                    </div>
                  </div>
                </div>
              </div>
              
              <div class="work-groups-actions">
                <a-button type="primary" @click="saveAssignment" block>
                  <template #icon><icon-save /></template>
                  保存分配
                </a-button>
                <a-button @click="goBackToStep2" block>
                  <template #icon><icon-arrow-left /></template>
                  返回编辑
                </a-button>
              </div>
            </a-card>
          </div>
        </div>
      </div>

      <!-- 证书查看弹窗 -->
      <a-modal
        v-model:visible="certificateModalVisible"
        title="工人证书"
        width="600px"
        :footer="false"
      >
        <div class="certificate-list">
          <div 
            v-for="cert in selectedWorkerCertificates" 
            :key="cert.id"
            class="certificate-item"
          >
            <div class="certificate-header">
              <h4>{{ cert.name }}</h4>
              <a-tag :color="getCertificateStatusColor(cert.status)">
                {{ getCertificateStatusText(cert.status) }}
              </a-tag>
            </div>
            <div class="certificate-details">
              <p><strong>证书编号：</strong>{{ cert.code }}</p>
              <p><strong>发证机构：</strong>{{ cert.issuingAuthority }}</p>
              <p><strong>发证日期：</strong>{{ cert.issueDate }}</p>
              <p><strong>有效期至：</strong>{{ cert.expiryDate }}</p>
            </div>
          </div>
        </div>
      </a-modal>

      <!-- 工作组详情弹窗 -->
      <a-modal
        v-model:visible="workGroupDetailModalVisible"
        title="工作组详情"
        width="800px"
        :footer="false"
      >
        <div class="work-group-detail">
          <div class="project-info-section">
            <h3>{{ selectedProjectForDetail?.projectName }}</h3>
            <p class="project-code">项目编号: {{ selectedProjectForDetail?.projectCode }}</p>
          </div>
          
          <div class="work-groups-section">
            <h4>工作组列表</h4>
            <div class="work-groups-detail-list">
              <div 
                v-for="workGroup in selectedProjectForDetail?.workGroups" 
                :key="workGroup.id"
                class="work-group-detail-item"
              >
                <div class="work-group-detail-header">
                  <h5>{{ workGroup.name }}</h5>
                  <div class="work-group-detail-stats">
                    <span class="member-count">{{ workGroup.memberCount }}/{{ workGroup.requiredCount }}</span>
                    <a-tag :color="getWorkGroupStatusColor(workGroup.status)" size="small">
                      {{ getWorkGroupStatusText(workGroup.status) }}
                    </a-tag>
                  </div>
                </div>
                
                <div class="work-group-detail-members" v-if="workGroup.members && workGroup.members.length > 0">
                  <div class="members-header">
                    <span>成员列表：</span>
                  </div>
                  <div class="members-grid">
                    <div 
                      v-for="member in workGroup.members" 
                      :key="member.id"
                      class="member-detail-item"
                    >
                      <a-avatar :src="member.avatar" :size="32">
                        {{ member.name.charAt(0) }}
                      </a-avatar>
                      <div class="member-detail-info">
                        <span class="member-name">{{ member.name }}</span>
                        <span class="member-role">{{ member.role }}</span>
                      </div>
                    </div>
                  </div>
                </div>
                
                <div class="work-group-detail-description" v-if="workGroup.description">
                  <p><strong>描述：</strong>{{ workGroup.description }}</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </a-modal>
    </div>
  </GiPageLayout>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { Message, Modal } from '@arco-design/web-vue'
import { 
  IconSearch, 
  IconRefresh, 
  IconApps,
  IconUserGroup,
  IconPlus,
  IconUserAdd,
  IconEdit,
  IconDelete,
  IconStarFill,
  IconCheckCircle,
  IconFolder,
  IconArrowRight,
  IconArrowLeft,
  IconCheck,
  IconFilter,
  IconClose,
  IconSave,
  IconEye
} from '@arco-design/web-vue/es/icon'
import type { 
  ProjectResp, 
  ConstructorResp, 
  CertificationResp,
  WorkGroup,
  WorkTypeGroup,
  WorkGroupMember,
  ProjectWithWorkGroups
} from '@/apis/project/type'
import { 
  getWorkGroupsByProject, 
  createWorkGroup as createWorkGroupAPI,
  assignWorkerToGroup,
  removeWorkerFromGroup
} from '@/apis/project/workGroup'

// 移除重复的类型定义，使用导入的类型
// interface WorkGroup {
//   id: string
//   name: string
//   description: string
//   projectId: string
//   status: 'ACTIVE' | 'INACTIVE' | 'COMPLETED'
//   workTypeGroups: WorkTypeGroup[]
//   memberCount: number
//   requiredCount: number
//   members?: WorkGroupMember[]
//   createTime: string
// }

// interface WorkTypeGroup {
//   name: string
//   requiredCount: number
//   priority: 'HIGH' | 'MEDIUM' | 'LOW'
// }

// interface WorkGroupMember {
//   id: string
//   name: string
//   role: string
//   avatar?: string
//   phone?: string
// }

// 扩展项目类型，包含工作组信息
// interface ProjectWithWorkGroups extends ProjectResp {
//   workGroups?: WorkGroup[]
// }

defineOptions({ name: 'PersonnelOrganization' })

// 步骤控制
const currentStep = ref(1)

// 项目数据
const projectList = ref<ProjectWithWorkGroups[]>([])
const selectedProject = ref<ProjectWithWorkGroups | null>(null)
const selectedProjectForDetail = ref<ProjectWithWorkGroups | null>(null)

// 工作组表单
const workGroupForm = reactive({
  id: '', // 添加工作组ID字段
  name: '',
  description: '',
  projectId: '',
  workTypeGroups: [
    {
      name: '',
      requiredCount: 1,
      priority: 'MEDIUM'
    }
  ]
})

// 工人数据
const workers = ref<ConstructorResp[]>([])
const filteredWorkers = ref<ConstructorResp[]>([])

// 筛选表单
const filterForm = reactive({
  workTypes: [] as string[],
  certificateKeyword: ''
})

// 分配数据
const workerAssignments = ref<Record<string, ConstructorResp[]>>({})

// 弹窗状态
const certificateModalVisible = ref(false)
const selectedWorkerCertificates = ref<CertificationResp[]>([])
const workGroupDetailModalVisible = ref(false)

// 拖拽状态
const draggedWorker = ref<ConstructorResp | null>(null)

// 计算属性
const getAssignedCount = (groupName: string) => {
  return workerAssignments.value[groupName]?.length || 0
}

const getGroupMembers = (groupName: string) => {
  return workerAssignments.value[groupName] || []
}

// 方法
const loadProjectList = async () => {
  try {
    // 使用模拟数据，包含工作组信息
    projectList.value = [
      {
        projectId: '1',
        projectCode: 'PRJ001',
        projectName: '风电场A区建设项目',
        farmName: '风电场A区',
        status: 1,
        statusLabel: '进行中',
        workGroups: [
          {
            id: 'wg1',
            name: '高空作业组',
            description: '负责塔上登高作业',
            projectId: '1',
            status: 'ACTIVE',
            workTypeGroups: [
              { name: '塔上登高作业', requiredCount: 5, priority: 'HIGH' }
            ],
            memberCount: 3,
            requiredCount: 5,
            members: [
              { id: 'm1', name: '张登高', role: '组长', avatar: '' },
              { id: 'm2', name: '李高空', role: '组员', avatar: '' },
              { id: 'm3', name: '王高空', role: '组员', avatar: '' }
            ],
            createTime: '2024-01-15'
          },
          {
            id: 'wg2',
            name: '地勤保障组',
            description: '负责地面保障工作',
            projectId: '1',
            status: 'ACTIVE',
            workTypeGroups: [
              { name: '地勤人员', requiredCount: 3, priority: 'MEDIUM' }
            ],
            memberCount: 2,
            requiredCount: 3,
            members: [
              { id: 'm4', name: '赵地勤', role: '组长', avatar: '' },
              { id: 'm5', name: '孙地勤', role: '组员', avatar: '' }
            ],
            createTime: '2024-01-16'
          }
        ]
      },
      {
        projectId: '2',
        projectCode: 'PRJ002',
        projectName: '风电场B区维护项目',
        farmName: '风电场B区',
        status: 2,
        statusLabel: '已完成',
        workGroups: [
          {
            id: 'wg3',
            name: '维护保养组',
            description: '负责设备维护保养',
            projectId: '2',
            status: 'COMPLETED',
            workTypeGroups: [
              { name: '机械工程师', requiredCount: 2, priority: 'HIGH' },
              { name: '电气工程师', requiredCount: 2, priority: 'HIGH' }
            ],
            memberCount: 4,
            requiredCount: 4,
            members: [
              { id: 'm6', name: '周机械', role: '机械工程师', avatar: '' },
              { id: 'm7', name: '吴电气', role: '电气工程师', avatar: '' },
              { id: 'm8', name: '郑机械', role: '机械工程师', avatar: '' },
              { id: 'm9', name: '王电气', role: '电气工程师', avatar: '' }
            ],
            createTime: '2024-01-10'
          }
        ]
      },
      {
        projectId: '3',
        projectCode: 'PRJ003',
        projectName: '风电场C区升级项目',
        farmName: '风电场C区',
        status: 0,
        statusLabel: '准备中',
        workGroups: []
      }
    ]
    
    // 为每个项目加载工作组信息
    for (const project of projectList.value) {
      try {
        const workGroups = await getWorkGroupsByProject(project.projectId)
        project.workGroups = workGroups
      } catch (error) {
        console.warn(`加载项目 ${project.projectName} 的工作组失败:`, error)
        // 保持模拟数据作为后备
      }
    }
  } catch (error) {
    Message.error('加载项目列表失败')
  }
}

const loadWorkers = async () => {
  try {
    // 模拟API调用
    workers.value = [
      {
        id: '1',
        name: '张登高',
        phone: '13800138001',
        email: 'zhangdg@example.com',
        avatar: '',
        workTypes: ['塔上登高作业'],
        certifications: [
          {
            id: '1',
            name: '高空作业证',
            type: '特种作业证',
            code: 'GK001',
            issueDate: '2023-01-01',
            expiryDate: '2025-01-01',
            issuingAuthority: '国家安全生产监督管理局',
            status: 'VALID'
          }
        ],
        experience: 8,
        status: 'ACTIVE',
        rating: 4.9,
        joinDate: '2023-01-01'
      },
      {
        id: '2',
        name: '李高空',
        phone: '13800138002',
        email: 'ligk@example.com',
        avatar: '',
        workTypes: ['塔上登高作业'],
        certifications: [
          {
            id: '2',
            name: '高空作业证',
            type: '特种作业证',
            code: 'GK002',
            issueDate: '2022-06-01',
            expiryDate: '2024-06-01',
            issuingAuthority: '国家安全生产监督管理局',
            status: 'VALID'
          }
        ],
        experience: 6,
        status: 'ACTIVE',
        rating: 4.7,
        joinDate: '2023-02-01'
      },
      {
        id: '3',
        name: '王地勤',
        phone: '13800138003',
        email: 'wangdq@example.com',
        avatar: '',
        workTypes: ['地勤人员'],
        certifications: [
          {
            id: '3',
            name: '安全员证',
            type: '安全资格证',
            code: 'AQ001',
            issueDate: '2023-03-01',
            expiryDate: '2025-03-01',
            issuingAuthority: '国家安全生产监督管理局',
            status: 'VALID'
          }
        ],
        experience: 5,
        status: 'ACTIVE',
        rating: 4.6,
        joinDate: '2023-03-01'
      },
      {
        id: '4',
        name: '赵飞手',
        phone: '13800138004',
        email: 'zhaofs@example.com',
        avatar: '',
        workTypes: ['无人机飞手'],
        certifications: [
          {
            id: '4',
            name: '无人机驾驶证',
            type: '飞行执照',
            code: 'WRJ001',
            issueDate: '2022-12-01',
            expiryDate: '2024-12-01',
            issuingAuthority: '中国民用航空局',
            status: 'VALID'
          }
        ],
        experience: 4,
        status: 'ACTIVE',
        rating: 4.8,
        joinDate: '2023-04-01'
      },
      {
        id: '5',
        name: '孙司机',
        phone: '13800138005',
        email: 'sunsj@example.com',
        avatar: '',
        workTypes: ['司机'],
        certifications: [
          {
            id: '5',
            name: 'A2驾驶证',
            type: '驾驶执照',
            code: 'JS001',
            issueDate: '2023-05-01',
            expiryDate: '2025-05-01',
            issuingAuthority: '交通管理局',
            status: 'VALID'
          }
        ],
        experience: 6,
        status: 'ACTIVE',
        rating: 4.6,
        joinDate: '2023-05-01'
      }
    ]
    filteredWorkers.value = workers.value
  } catch (error) {
    Message.error('加载工人列表失败')
  }
}

const selectProject = (project: ProjectWithWorkGroups) => {
  selectedProject.value = project
}

const enterWorkGroupCreation = (project: ProjectWithWorkGroups) => {
  selectedProject.value = project
  workGroupForm.projectId = project.projectId
  currentStep.value = 2
}

const addWorkTypeGroup = () => {
  workGroupForm.workTypeGroups.push({
    name: '',
    requiredCount: 1,
    priority: 'MEDIUM'
  })
}

const removeWorkTypeGroup = (index: number) => {
  if (workGroupForm.workTypeGroups.length > 1) {
    workGroupForm.workTypeGroups.splice(index, 1)
  }
}

const goBackToStep1 = () => {
  currentStep.value = 1
  selectedProject.value = null
  resetWorkGroupForm()
}

const goBackToStep2 = () => {
  currentStep.value = 2
}

const createWorkGroup = async () => {
  if (!workGroupForm.name || !workGroupForm.projectId) {
    Message.warning('请填写工作组名称和关联项目')
    return
  }
  
  const hasEmptyGroups = workGroupForm.workTypeGroups.some(group => !group.name)
  if (hasEmptyGroups) {
    Message.warning('请填写所有工种分组名称')
    return
  }
  
  try {
    // 调用API创建工作组
    const newWorkGroup = await createWorkGroupAPI({
      name: workGroupForm.name,
      description: workGroupForm.description,
      projectId: workGroupForm.projectId,
      workTypeGroups: workGroupForm.workTypeGroups
    })
    
    Message.success('工作组创建成功')
    
    // 保存新创建的工作组ID
    workGroupForm.id = newWorkGroup.id
    
    // 更新项目的工作组列表
    if (selectedProject.value) {
      if (!selectedProject.value.workGroups) {
        selectedProject.value.workGroups = []
      }
      selectedProject.value.workGroups.push(newWorkGroup)
    }
    
    currentStep.value = 3
    loadWorkers()
  } catch (error) {
    Message.error('创建工作组失败')
    console.error('创建工作组错误:', error)
  }
}

const resetWorkGroupForm = () => {
  workGroupForm.id = '' // 重置工作组ID
  workGroupForm.name = ''
  workGroupForm.description = ''
  workGroupForm.projectId = ''
  workGroupForm.workTypeGroups = [
    {
      name: '',
      requiredCount: 1,
      priority: 'MEDIUM'
    }
  ]
}

const handleFilterChange = () => {
  let filtered = workers.value
  
  // 按工种筛选
  if (filterForm.workTypes.length > 0) {
    filtered = filtered.filter(worker => 
      worker.workTypes.some(workType => filterForm.workTypes.includes(workType))
    )
  }
  
  // 按证书关键词搜索
  if (filterForm.certificateKeyword) {
    const keyword = filterForm.certificateKeyword.toLowerCase()
    filtered = filtered.filter(worker => 
      worker.certifications.some(cert => 
        cert.name.toLowerCase().includes(keyword)
      )
    )
  }
  
  filteredWorkers.value = filtered
}

const resetFilter = () => {
  filterForm.workTypes = []
  filterForm.certificateKeyword = ''
  filteredWorkers.value = workers.value
}

const handleDragStart = (event: DragEvent, worker: ConstructorResp) => {
  draggedWorker.value = worker
  if (event.dataTransfer) {
    event.dataTransfer.effectAllowed = 'move'
  }
}

const handleDragEnd = () => {
  draggedWorker.value = null
}

const handleDragOver = (event: DragEvent) => {
  event.preventDefault()
  if (event.dataTransfer) {
    event.dataTransfer.dropEffect = 'move'
  }
}

const handleDrop = (event: DragEvent, group: any) => {
  event.preventDefault()
  
  if (!draggedWorker.value) return
  
  const groupName = group.name
  if (!workerAssignments.value[groupName]) {
    workerAssignments.value[groupName] = []
  }
  
  // 检查是否已分配
  const isAlreadyAssigned = Object.values(workerAssignments.value).some(
    members => members.some(member => member.id === draggedWorker.value?.id)
  )
  
  if (isAlreadyAssigned) {
    Message.warning('该工人已被分配到其他组')
    return
  }
  
  // 检查是否超过需求人数
  if (workerAssignments.value[groupName].length >= group.requiredCount) {
    Message.warning('该工种分组人数已满')
    return
  }

  workerAssignments.value[groupName].push(draggedWorker.value)
  Message.success(`已将 ${draggedWorker.value.name} 分配到 ${groupName}`)
}

const removeFromGroup = async (member: ConstructorResp, groupName: string) => {
  try {
    if (!workGroupForm.id) {
      Message.error('工作组ID不存在')
      return
    }
    
    await removeWorkerFromGroup({
      workGroupId: workGroupForm.id,
      workerId: member.id,
      workTypeName: groupName
    })
    
    // 从本地分配数据中移除
    const index = workerAssignments.value[groupName].findIndex(m => m.id === member.id)
    if (index > -1) {
      workerAssignments.value[groupName].splice(index, 1)
    }
    
    Message.success(`已从 ${groupName} 移除 ${member.name}`)
  } catch (error) {
    Message.error('移除工人失败')
    console.error('移除工人错误:', error)
  }
}

const viewWorkerCertificates = async (worker: ConstructorResp) => {
  try {
    // 使用本地证书数据
    selectedWorkerCertificates.value = worker.certifications
    certificateModalVisible.value = true
  } catch (error) {
    Message.error('加载证书信息失败')
  }
}

const saveAssignment = async () => {
  try {
    // 模拟保存分配
    const totalAssigned = Object.values(workerAssignments.value).reduce(
      (sum, members) => sum + members.length, 0
    )
    
    if (totalAssigned === 0) {
      Message.warning('请至少分配一名工人')
      return
    }

    if (!workGroupForm.id) {
      Message.error('工作组ID不存在')
      return
    }

    // 调用API保存分配结果
    const assignmentPromises = []
    
    for (const [workTypeName, workers] of Object.entries(workerAssignments.value)) {
      if (workers.length > 0) {
        const workerIds = workers.map(w => w.id)
        assignmentPromises.push(
          assignWorkerToGroup({
            workGroupId: workGroupForm.id,
            workerIds,
            workTypeName
          })
        )
      }
    }
    
    await Promise.all(assignmentPromises)
    Message.success('分配保存成功')
    
    // 刷新项目的工作组信息
    if (selectedProject.value) {
      try {
        const workGroups = await getWorkGroupsByProject(selectedProject.value.projectId)
        selectedProject.value.workGroups = workGroups
      } catch (error) {
        console.warn('刷新工作组信息失败:', error)
      }
    }
  } catch (error) {
    Message.error('保存分配失败')
    console.error('保存分配错误:', error)
  }
}

const viewProjectWorkGroups = (project: ProjectWithWorkGroups) => {
  selectedProjectForDetail.value = project
  workGroupDetailModalVisible.value = true
}

// 工具方法
const getStatusColor = (status: number) => {
  const statusMap: Record<number, string> = {
    0: 'orange',
    1: 'blue',
    2: 'green'
  }
  return statusMap[status] || 'gray'
}

const getWorkerStatusColor = (status: string) => {
  const statusMap: Record<string, string> = {
    'ACTIVE': 'green',
    'INACTIVE': 'red',
    'BUSY': 'orange'
  }
  return statusMap[status] || 'gray'
}

const getWorkerStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    'ACTIVE': '可用',
    'INACTIVE': '不可用',
    'BUSY': '忙碌中'
  }
  return statusMap[status] || status
}

const getCertificateStatusColor = (status: string) => {
  const statusMap: Record<string, string> = {
    'VALID': 'green',
    'EXPIRED': 'red',
    'EXPIRING_SOON': 'orange'
  }
  return statusMap[status] || 'gray'
}

const getCertificateStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    'VALID': '有效',
    'EXPIRED': '已过期',
    'EXPIRING_SOON': '即将过期'
  }
  return statusMap[status] || status
}

const getWorkGroupStatusColor = (status: string) => {
  const statusMap: Record<string, string> = {
    'ACTIVE': 'green',
    'INACTIVE': 'red',
    'COMPLETED': 'gray'
  }
  return statusMap[status] || 'gray'
}

const getWorkGroupStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    'ACTIVE': '进行中',
    'INACTIVE': '已暂停',
    'COMPLETED': '已完成'
  }
  return statusMap[status] || status
}

// 生命周期
onMounted(async () => {
    await loadProjectList()
})
</script>

<style scoped lang="scss">
.personnel-organization-container {
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: 100vh;
  overflow-y: auto; // 添加垂直滚动
}

// 流程导航样式
.process-flow {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 30px;
  padding: 20px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  flex-shrink: 0; // 防止压缩
}

.flow-step {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 16px 24px;
  border-radius: 12px;
  transition: all 0.3s ease;
  opacity: 0.6;
  
  &.active {
    opacity: 1;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
  }
  
  .step-icon {
    font-size: 24px;
    margin-bottom: 8px;
  }
  
  .step-text {
    font-size: 14px;
    font-weight: 600;
  }
}

.flow-arrow {
  font-size: 24px;
  color: #667eea;
  margin: 0 20px;
  font-weight: bold;
}

.step-content {
  max-width: 1200px;
  margin: 0 auto;
  margin-bottom: 30px; // 添加底部间距
}

// 项目选择卡片
.project-selection-card {
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  
  .card-title {
    display: flex;
    align-items: center;
    gap: 12px;
    font-size: 18px;
    font-weight: 600;
    color: #1d2129;
  }
}

.project-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
  gap: 24px;
  margin-top: 20px;
}

.project-card {
  background: white;
  border: 2px solid #f0f0f0;
  border-radius: 16px;
  padding: 24px;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:hover {
    border-color: #667eea;
    box-shadow: 0 8px 25px rgba(102, 126, 234, 0.15);
    transform: translateY(-2px);
  }
  
  &.selected {
    border-color: #667eea;
    background: linear-gradient(135deg, #f8f9ff 0%, #f0f4ff 100%);
    box-shadow: 0 8px 25px rgba(102, 126, 234, 0.2);
  }
}

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

.project-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 20px;
}
  
.project-info {
  margin-bottom: 20px;
  
  .project-name {
    margin: 0 0 8px 0;
    font-size: 18px;
    font-weight: 600;
    color: #1d2129;
  }
      
  .project-code {
    margin: 0 0 4px 0;
    font-size: 14px;
    color: #86909c;
  }
      
  .project-farm {
    margin: 0;
    font-size: 14px;
    color: #4e5969;
  }
}

.project-work-groups {
  margin-top: 20px;
  padding-top: 16px;
  border-top: 1px solid #e9ecef;

  .work-groups-header {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 16px;
    font-weight: 600;
    color: #1d2129;
    margin-bottom: 12px;
  }

  .work-groups-list {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
  }

  .work-group-preview {
    background: #f8f9fa;
    border: 1px solid #e9ecef;
    border-radius: 8px;
    padding: 8px 12px;
    font-size: 14px;
    color: #1d2129;
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .more-work-groups {
    font-size: 14px;
    color: #86909c;
    font-weight: 500;
  }
}

.project-actions {
  text-align: center;
  margin-top: 20px;
}

// 工作组创建表单
.work-group-form-card {
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  
  .card-title {
    display: flex;
    align-items: center;
    gap: 12px;
    font-size: 18px;
    font-weight: 600;
    color: #1d2129;
    
    .project-info-text {
      color: #86909c;
      font-weight: 400;
    }
  }
}

.work-group-form {
  max-width: 800px;
  margin: 0 auto;
}

.work-type-groups {
  .work-type-group-item {
    margin-bottom: 16px;
    padding: 16px;
    background: #f8f9fa;
    border-radius: 8px;
    border: 1px solid #e9ecef;
  }
}

.add-work-type-group {
  margin-top: 16px;
}

.form-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 32px;
  padding-top: 24px;
  border-top: 1px solid #e9ecef;
}

// 工人分配布局
.worker-assignment-layout {
  display: grid;
  grid-template-columns: 280px 1fr 320px;
  gap: 24px;
  min-height: 600px; // 设置最小高度而不是固定高度
}

.filter-sidebar,
.work-groups-sidebar {
  .filter-card,
  .work-groups-card {
    height: 100%;
    border-radius: 16px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);

    .card-title {
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 16px;
      font-weight: 600;
    }
  }
}

.filter-content {
  .arco-form-item {
    margin-bottom: 20px;
  }
}

.worker-table-section {
  .worker-table-card {
    height: 100%;
    border-radius: 16px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
    
    .card-title {
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 16px;
      font-weight: 600;
  
      .worker-count {
        color: #86909c;
        font-weight: 400;
      }
    }
  }
}

.worker-table {
  max-height: 500px; // 设置最大高度
  overflow-y: auto; // 添加垂直滚动
  padding: 16px;
}

.worker-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 20px;
  background: white;
  border: 2px solid #f0f0f0;
  border-radius: 16px;
  margin-bottom: 16px;
  cursor: grab;
  transition: all 0.3s ease;
  
  &:hover {
    border-color: #667eea;
    box-shadow: 0 8px 25px rgba(102, 126, 234, 0.15);
    transform: translateY(-2px);
  }
  
  &:active {
    cursor: grabbing;
  }
}

.worker-info {
  flex: 1;
}

.worker-name {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
  
  h4 {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
    color: #1d2129;
  }
}

.worker-details {
  display: flex;
  gap: 20px;
  margin-bottom: 12px;
  font-size: 13px;
  color: #86909c;
  
  .phone, .experience, .rating {
    display: flex;
    align-items: center;
    gap: 4px;
  }
}

.worker-skills {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
}

.worker-certificates {
  min-width: 200px;
  
  .certificates-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
      
    .label {
      font-size: 12px;
      color: #86909c;
      font-weight: 500;
    }
  }
  
  .certificates-preview {
    display: flex;
    gap: 6px;
    flex-wrap: wrap;
    
    .more-certs {
      font-size: 11px;
      color: #86909c;
      font-weight: 500;
      align-self: center;
    }
  }
}

// 工种分组
.work-groups-content {
  max-height: 400px; // 设置最大高度
  overflow-y: auto; // 添加垂直滚动
  padding: 16px;
}
    
.work-group-drop-zone {
  background: white;
  border: 2px dashed #d9d9d9;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 16px;
  transition: all 0.3s ease;
      
  &:hover {
    border-color: #667eea;
    background: #f8f9ff;
  }
}
      
.work-group-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
        
  h4 {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
    color: #1d2129;
  }
          
  .work-group-stats {
    font-size: 14px;
    font-weight: 600;
    
    .assigned {
      color: #52c41a;
    }
    
    .separator {
      margin: 0 4px;
      color: #86909c;
    }
          
    .required {
      color: #1890ff;
    }
  }
}

.work-group-members {
  min-height: 60px;
}

.group-member {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px 12px;
  background: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 8px;
          
  .member-name {
    flex: 1;
    font-size: 14px;
    color: #1d2129;
  }
}

.drop-hint {
  text-align: center;
  padding: 20px;
  color: #86909c;
  font-size: 14px;
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  background: #fafafa;
}

.work-groups-actions {
  padding: 16px;
  border-top: 1px solid #e9ecef;
  
  .arco-btn {
    margin-bottom: 12px;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
}

// 证书弹窗
.certificate-list {
  max-height: 400px;
  overflow-y: auto;
}

.certificate-item {
  border: 1px solid #e5e6eb;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 12px;
}

.certificate-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  
  h4 {
    margin: 0;
    font-size: 14px;
    font-weight: 600;
  }
}

.certificate-details {
  p {
    margin: 4px 0;
    font-size: 12px;
    color: #4e5969;
  }
}

// 工作组详情弹窗
.work-group-detail {
  .project-info-section {
    margin-bottom: 20px;
    padding-bottom: 16px;
    border-bottom: 1px solid #e9ecef;

    h3 {
      margin: 0 0 8px 0;
      font-size: 18px;
      font-weight: 600;
      color: #1d2129;
    }

    .project-code {
      font-size: 14px;
      color: #86909c;
    }
  }

  .work-groups-section {
    h4 {
      margin: 0 0 16px 0;
      font-size: 16px;
      font-weight: 600;
      color: #1d2129;
    }

    .work-groups-detail-list {
      .work-group-detail-item {
        background: #f8f9fa;
        border: 1px solid #e9ecef;
        border-radius: 8px;
        padding: 16px;
        margin-bottom: 16px;

        .work-group-detail-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 12px;

          h5 {
            margin: 0;
            font-size: 15px;
            font-weight: 600;
            color: #1d2129;
          }

          .work-group-detail-stats {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 14px;
            color: #86909c;

            .member-count {
              color: #52c41a;
            }
          }
        }

        .work-group-detail-members {
          .members-header {
            margin-bottom: 12px;
            font-size: 14px;
            color: #1d2129;
            font-weight: 500;
          }

          .members-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
            gap: 12px;
          }

          .member-detail-item {
            display: flex;
            align-items: center;
            gap: 12px;

            .member-detail-info {
              .member-name {
                font-size: 14px;
                color: #1d2129;
                font-weight: 600;
              }
              .member-role {
                font-size: 12px;
                color: #86909c;
              }
            }
          }
        }

        .work-group-detail-description {
          p {
            margin: 0;
            font-size: 13px;
            color: #4e5969;
          }
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .worker-assignment-layout {
    grid-template-columns: 250px 1fr 280px;
    gap: 16px;
  }
}

@media (max-width: 992px) {
  .worker-assignment-layout {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .filter-sidebar,
  .work-groups-sidebar {
    order: 2;
  }
  
  .worker-table-section {
    order: 1;
  }
}

@media (max-width: 768px) {
  .personnel-organization-container {
    padding: 16px;
  }
  
  .project-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .process-flow {
    flex-direction: column;
    gap: 16px;
    
    .flow-arrow {
      transform: rotate(90deg);
    }
  }
}
</style>
