<!--
  团队成员管理页面
  功能特性:
  1. 团队成员列表展示
  2. 新增团队成员
  3. 编辑团队成员信息
  4. 删除团队成员
  5. 导入导出团队成员数据
-->
<template>
  <GiPageLayout class="construction-personnel-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <a-button @click="$router.back()" class="back-btn">
          <template #icon><icon-left /></template>
          返回
        </a-button>
        <div class="header-title">
          <icon-user-group class="title-icon" />
          <h1>团队成员管理</h1>
          <span v-if="projectId" class="project-info">项目ID: {{ projectId }}</span>
        </div>
      </div>
      <div class="header-actions">
        <a-button type="primary" @click="openAddModal">
          <template #icon><icon-plus /></template>
          新增成员
        </a-button>
        <a-button @click="openImportModal">
          <template #icon><icon-upload /></template>
          导入
        </a-button>
        <a-button @click="exportData">
          <template #icon><icon-download /></template>
          导出
        </a-button>
      </div>
    </div>

    <!-- 简洁搜索区域 -->
    <div class="search-section">
      <a-card :bordered="false" class="search-card">
        <a-form layout="inline" :model="searchForm">
          <a-form-item label="姓名">
            <a-input 
              v-model="searchForm.name" 
              placeholder="请输入姓名" 
              style="width: 180px"
              allow-clear
              @press-enter="handleSearch"
            />
          </a-form-item>
          <a-form-item label="岗位">
            <a-select 
              v-model="searchForm.position" 
              placeholder="请选择岗位" 
              style="width: 150px"
              allow-clear
            >
              <a-option 
                v-for="option in POSITION_OPTIONS" 
                :key="option.value" 
                :value="option.value"
              >
                {{ option.label }}
              </a-option>
            </a-select>
          </a-form-item>
          <a-form-item label="状态">
            <a-select 
              v-model="searchForm.status" 
              placeholder="请选择状态" 
              style="width: 120px"
              allow-clear
            >
              <a-option 
                v-for="option in STATUS_OPTIONS" 
                :key="option.value" 
                :value="option.value"
              >
                {{ option.label }}
              </a-option>
            </a-select>
          </a-form-item>
          <a-form-item>
            <a-space>
              <a-button type="primary" @click="handleSearch">
                <template #icon><icon-search /></template>
                搜索
              </a-button>
              <a-button @click="handleReset">
                <template #icon><icon-refresh /></template>
                重置
              </a-button>
            </a-space>
          </a-form-item>
        </a-form>
      </a-card>
    </div>

    <!-- 数据表格 -->
    <GiTable
      row-key="id"
      :data="dataList"
      :columns="tableColumns"
      :loading="loading"
      :scroll="{ x: '100%', minWidth: 1200 }"
      :pagination="pagination"
      :disabled-tools="['size']"
      @page-change="onPageChange"
      @page-size-change="onPageSizeChange"
      @refresh="loadData"
    >
      <!-- 状态列 -->
      <template #status="{ record }">
        <a-tag :color="getStatusColor(record.status || 'offline')">
          {{ getStatusText(record.status || 'offline') }}
        </a-tag>
      </template>



      <!-- 备注列 -->
      <template #remark="{ record }">
        <div class="remark-content" v-if="record.remark">
          {{ record.remark }}
        </div>
        <span v-else class="no-remark">暂无备注</span>
      </template>

      <!-- 操作列 -->
      <template #action="{ record }">
        <a-space>
          <a-link title="编辑" @click="openEditModal(record)">编辑</a-link>
          <a-link title="状态调整" @click="openStatusModal(record)">状态</a-link>
          <a-link status="danger" title="删除" @click="confirmDelete(record)">删除</a-link>
        </a-space>
      </template>
    </GiTable>

    <!-- 新增/编辑弹窗 -->
    <a-modal
      v-model:visible="memberModalVisible"
      :title="isEdit ? '编辑团队成员' : '新增团队成员'"
      width="600px"
      @ok="saveMember"
      @cancel="cancelMember"
    >
      <div class="member-form">
        <div class="form-row">
          <div class="form-item">
            <label>姓名 <span class="required">*</span></label>
            <a-input v-model="memberForm.name" placeholder="请输入姓名" />
          </div>
          <div class="form-item">
            <label>联系电话 <span class="required">*</span></label>
            <a-input v-model="memberForm.phone" placeholder="请输入联系电话" />
          </div>
        </div>
        <div class="form-row">
          <div class="form-item">
            <label>岗位 <span class="required">*</span></label>
            <a-select v-model="memberForm.position" placeholder="请选择岗位">
              <a-option 
                v-for="option in POSITION_OPTIONS" 
                :key="option.value" 
                :value="option.value"
              >
                {{ option.label }}
              </a-option>
            </a-select>
          </div>
          <div class="form-item">
            <label>状态</label>
            <a-select v-model="memberForm.status" placeholder="请选择状态">
              <a-option 
                v-for="option in STATUS_OPTIONS" 
                :key="option.value" 
                :value="option.value"
              >
                {{ option.label }}
              </a-option>
            </a-select>
          </div>
        </div>
        <div class="form-row">
          <div class="form-item">
            <label>邮箱</label>
            <a-input v-model="memberForm.email" placeholder="请输入邮箱" />
          </div>
          <div class="form-item">
            <label>入职日期</label>
            <a-date-picker v-model="memberForm.joinDate" placeholder="请选择入职日期" />
          </div>
        </div>

        <div class="form-item">
          <label>备注信息</label>
          <a-textarea 
            v-model="memberForm.remark" 
            placeholder="请输入备注信息，格式：主要负责：项目经理，次要负责：安全员等"
            :rows="3"
          />
        </div>
      </div>
    </a-modal>

    <!-- 状态调整弹窗 -->
    <a-modal
      v-model:visible="statusModalVisible"
      title="调整状态"
      width="400px"
      @ok="saveStatus"
      @cancel="cancelStatus"
    >
      <div class="status-form">
        <div class="form-item">
          <label>成员姓名:</label>
          <span>{{ statusForm.name }}</span>
        </div>
        <div class="form-item">
          <label>当前状态:</label>
          <span>{{ getStatusText(statusForm.currentStatus) }}</span>
        </div>
        <div class="form-item">
          <label>新状态:</label>
          <a-select v-model="statusForm.newStatus" placeholder="请选择新状态">
            <a-option 
              v-for="option in STATUS_OPTIONS" 
              :key="option.value" 
              :value="option.value"
            >
              {{ option.label }}
            </a-option>
          </a-select>
        </div>
      </div>
    </a-modal>

    <!-- 导入弹窗 -->
    <a-modal
      v-model:visible="importModalVisible"
      title="导入团队成员"
      width="500px"
      @ok="confirmImport"
      @cancel="cancelImport"
    >
      <div class="import-form">
        <div class="form-item">
          <label>选择文件:</label>
          <a-upload
            v-model:file-list="fileList"
            :custom-request="customUpload"
            :show-file-list="true"
            accept=".xlsx,.xls,.csv"
            :limit="1"
          >
            <a-button>
              <template #icon><icon-upload /></template>
              选择文件
            </a-button>
          </a-upload>
        </div>
        <div class="form-item">
          <label>下载模板:</label>
          <a-button type="text" @click="downloadTemplate">
            <template #icon><icon-download /></template>
            下载导入模板
          </a-button>
        </div>
      </div>
    </a-modal>
  </GiPageLayout>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { Message, Modal } from '@arco-design/web-vue'
import { useRoute } from 'vue-router'
import type { TeamMemberResp, TeamMemberQuery, TeamMemberExportQuery, CreateTeamMemberForm, UpdateTeamMemberForm, BackendTeamMemberResp } from '@/apis/project/type'
import { 
  getProjectTeamMembers, 
  createTeamMember, 
  updateTeamMember, 
  deleteTeamMembers,
  importTeamMembers,
  exportTeamMembers,
  downloadImportTemplate
} from '@/apis/project/personnel-dispatch'

// 获取路由参数
const route = useRoute()
const projectId = route.query.projectId as string

// 选项数据常量
const POSITION_OPTIONS = [
  { label: '项目经理', value: '项目经理' },
  { label: '技术负责人', value: '技术负责人' },
  { label: '安全员', value: '安全员' },
  { label: '质量员', value: '质量员' },
  { label: '施工员', value: '施工员' },
  { label: '材料员', value: '材料员' },
  { label: '资料员', value: '资料员' },
  { label: '实习生', value: '实习生' },
  { label: '技术工人', value: '技术工人' },
  { label: '普通工人', value: '普通工人' }
]

const STATUS_OPTIONS = [
  { label: '可用', value: 'available' },
  { label: '忙碌', value: 'busy' },
  { label: '离线', value: 'offline' }
]

// 响应式数据
const loading = ref(false)
const dataList = ref<TeamMemberResp[]>([])
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: true,
  showJumper: true,
  showPageSize: true
})

// 搜索表单
const searchForm = reactive<{
  name: string
  position: string
  status: string
}>({
  name: '',
  position: '',
  status: ''
})

// 表格列配置
const tableColumns = [
  { title: '姓名', dataIndex: 'name', width: 100, fixed: 'left' },
  { title: '联系电话', dataIndex: 'phone', width: 120 },
  { title: '邮箱', dataIndex: 'email', width: 150 },
  { title: '项目岗位', dataIndex: 'position', width: 120 },
  { title: '状态', dataIndex: 'status', width: 100, slotName: 'status' },
  { title: '入职日期', dataIndex: 'joinDate', width: 120 },
  { title: '备注', dataIndex: 'remark', width: 200, slotName: 'remark' },
  { title: '操作', dataIndex: 'action', width: 180, fixed: 'right', slotName: 'action' }
]

// 弹窗状态
const memberModalVisible = ref(false)
const statusModalVisible = ref(false)
const importModalVisible = ref(false)
const isEdit = ref(false)

// 表单数据
const memberForm = reactive<CreateTeamMemberForm & { id?: string | number }>({
  projectId: projectId,
  name: '',
  phone: '',
  email: '',
  position: '',
  status: 'available',
  joinDate: '',
  remark: ''
})

const statusForm = reactive<{
  id: string | number
  name: string
  currentStatus: string
  newStatus: 'available' | 'busy' | 'offline'
}>({
  id: '',
  name: '',
  currentStatus: '',
  newStatus: 'available'
})

const fileList = ref<any[]>([])

// 方法
const loadData = async () => {
  if (!projectId) {
    console.warn('未获取到项目ID，无法加载团队成员数据')
    Message.warning('未获取到项目信息，请从项目详情页面进入')
    return
  }

  loading.value = true
  try {
    console.log('正在加载项目团队成员数据，项目ID:', projectId)
    
    // 构建查询参数
    const queryParams: TeamMemberQuery = {
      projectId: projectId,
      page: pagination.current,
      pageSize: pagination.pageSize,
      name: searchForm.name || undefined,
      position: searchForm.position || undefined,
      status: searchForm.status || undefined
    }
    
    const response = await getProjectTeamMembers(queryParams)
    
    console.log('API响应数据:', response.data)
    
    // 确保response.data是数组
    const rawData = Array.isArray(response.data) ? response.data : [response.data]
    
    console.log('处理后的原始数据:', rawData)
    
    // 处理后端返回的数据，将后端字段映射到前端期望的字段
    const mappedData = rawData.map((item: BackendTeamMemberResp) => {
      const mappedItem: TeamMemberResp = {
        id: item.memberId,
        name: item.name || '',
        phone: item.phone || '',
        email: item.email || '',
        position: item.position || '',
        status: (item.status === 'ACTIVE' ? 'available' : item.status === 'BUSY' ? 'busy' : 'offline') as 'available' | 'busy' | 'offline',
        joinDate: item.joinDate || '',
        remark: item.remark || '',
        avatar: item.userAvatar || ''
      }
      console.log('映射后的数据项:', mappedItem)
      return mappedItem
    })
    
    dataList.value = mappedData
    pagination.total = mappedData.length
    
    console.log('团队成员数据加载完成，显示数据:', dataList.value.length, '条，总计:', pagination.total, '条')
    
  } catch (error) {
    console.error('团队成员数据加载失败:', error)
    Message.error('团队成员数据加载失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = async () => {
  pagination.current = 1
  await loadData()
}

const handleReset = () => {
  console.log('重置搜索表单')
  Object.assign(searchForm, {
    name: '',
    position: '',
    status: ''
  })
  pagination.current = 1
  loadData()
}

const onPageChange = (page: number) => {
  pagination.current = page
  loadData()
}

const onPageSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize
  pagination.current = 1
  loadData()
}

const openAddModal = () => {
  isEdit.value = false
  resetMemberForm()
  memberModalVisible.value = true
}

const openEditModal = (record: TeamMemberResp) => {
  isEdit.value = true
  Object.assign(memberForm, {
    id: record.id,
    projectId: projectId,
    name: record.name,
    phone: record.phone || '',
    email: record.email || '',
    position: record.position,
    status: record.status || 'available',
    joinDate: record.joinDate || '',
    remark: record.remark || ''
  })
  memberModalVisible.value = true
}

const saveMember = async () => {
  if (!memberForm.name || !memberForm.phone || !memberForm.position) {
    Message.error('请填写必填项')
    return
  }

  try {
    if (isEdit.value && memberForm.id) {
      // 更新团队成员
      const updateData: UpdateTeamMemberForm = {
        name: memberForm.name,
        phone: memberForm.phone,
        email: memberForm.email,
        position: memberForm.position,
        status: memberForm.status,
        joinDate: memberForm.joinDate,
        remark: memberForm.remark
      }
      await updateTeamMember(memberForm.id, updateData)
      Message.success('更新成功')
    } else {
      // 创建团队成员
      const createData: CreateTeamMemberForm = {
        projectId: projectId,
        name: memberForm.name,
        phone: memberForm.phone,
        email: memberForm.email,
        position: memberForm.position,
        status: memberForm.status,
        joinDate: memberForm.joinDate,
        remark: memberForm.remark
      }
      await createTeamMember(createData)
      Message.success('添加成功')
    }
    
    memberModalVisible.value = false
    loadData()
  } catch (error) {
    console.error('保存团队成员失败:', error)
    Message.error(isEdit.value ? '更新失败' : '添加失败')
  }
}

const cancelMember = () => {
  memberModalVisible.value = false
  resetMemberForm()
}

const resetMemberForm = () => {
  Object.assign(memberForm, {
    id: undefined,
    projectId: projectId,
    name: '',
    phone: '',
    email: '',
    position: '',
    status: 'available',
    joinDate: '',
    remark: ''
  })
}

const openStatusModal = (record: TeamMemberResp) => {
  Object.assign(statusForm, {
    id: record.id,
    name: record.name,
    currentStatus: record.status || 'available',
    newStatus: record.status || 'available'
  })
  statusModalVisible.value = true
}

const saveStatus = async () => {
  try {
    await updateTeamMember(statusForm.id, { 
      status: statusForm.newStatus as 'available' | 'busy' | 'offline' 
    })
    Message.success('状态更新成功')
    statusModalVisible.value = false
    loadData()
  } catch (error) {
    console.error('状态更新失败:', error)
    Message.error('状态更新失败')
  }
}

const cancelStatus = () => {
  statusModalVisible.value = false
}

const confirmDelete = (record: TeamMemberResp) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除团队成员"${record.name}"吗？`,
    onOk: async () => {
      try {
        await deleteTeamMembers(record.id)
        Message.success('删除成功')
        loadData()
      } catch (error) {
        console.error('删除失败:', error)
        Message.error('删除失败')
      }
    }
  })
}

const openImportModal = () => {
  importModalVisible.value = true
}

const customUpload = (options: any) => {
  const { file } = options
  fileList.value = [file]
}

const confirmImport = async () => {
  if (fileList.value.length === 0) {
    Message.error('请选择要导入的文件')
    return
  }

  try {
    const file = fileList.value[0].originFileObj
    await importTeamMembers(projectId, file)
    Message.success('导入成功')
    importModalVisible.value = false
    fileList.value = []
    loadData()
  } catch (error) {
    console.error('导入失败:', error)
    Message.error('导入失败')
  }
}

const cancelImport = () => {
  importModalVisible.value = false
  fileList.value = []
}

const downloadTemplate = async () => {
  try {
    const response = await downloadImportTemplate()
    const blob = new Blob([response.data], { 
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
    })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = '团队成员导入模板.xlsx'
    link.click()
    window.URL.revokeObjectURL(url)
    Message.success('模板下载成功')
  } catch (error) {
    console.error('模板下载失败:', error)
    Message.error('模板下载失败')
  }
}

const exportData = async () => {
  try {
    const queryParams: TeamMemberExportQuery = {
      projectId: projectId,
      name: searchForm.name || undefined,
      position: searchForm.position || undefined,
      status: searchForm.status || undefined
    }
    
    const response = await exportTeamMembers(queryParams)
    const blob = new Blob([response.data], { 
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
    })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `团队成员数据_${new Date().toISOString().split('T')[0]}.xlsx`
    link.click()
    window.URL.revokeObjectURL(url)
    Message.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    Message.error('导出失败')
  }
}

// 工具方法
const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    available: 'green',
    busy: 'orange',
    offline: 'gray'
  }
  return colorMap[status] || 'gray'
}

const getStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    available: '可用',
    busy: '忙碌',
    offline: '离线'
  }
  return textMap[status] || '未知'
}

// 生命周期
onMounted(() => {
  console.log('团队成员管理页面加载，项目ID:', projectId)
  if (projectId) {
    loadData()
  } else {
    console.warn('未获取到项目ID，无法加载团队成员数据')
    Message.warning('未获取到项目信息，请从项目详情页面进入')
  }
})
</script>

<style lang="scss" scoped>
// 确保页面可以正常滚动
:deep(.gi-page-layout) {
  height: auto !important;
  min-height: 100vh;
  overflow-y: visible;
}

:deep(.gi-page-layout__body) {
  height: auto !important;
  overflow-y: visible;
}

// 确保全局滚动正常
:deep(body), :deep(html) {
  overflow-y: auto !important;
  height: auto !important;
}

// 确保页面容器可以滚动
:deep(.app-main), :deep(.main-content), :deep(.layout-content) {
  overflow-y: auto !important;
  height: auto !important;
}

// 确保表格容器可以滚动
:deep(.arco-table-container) {
  overflow-x: auto;
  overflow-y: visible;
}
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);

  .header-left {
    display: flex;
    align-items: center;
    gap: 16px;

    .back-btn {
      border: none;
      background: #f7f8fa;
      color: #4e5969;
      
      &:hover {
        background: #e5e6eb;
        color: #1d2129;
      }
    }

    .header-title {
      display: flex;
      align-items: center;
      gap: 8px;

      .title-icon {
        font-size: 24px;
        color: #667eea;
      }

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

      .project-info {
        font-size: 14px;
        color: #969fa8;
      }
    }
  }

  .header-actions {
    display: flex;
    gap: 12px;
  }
}

.search-section {
  margin-bottom: 16px;
  
  .search-card {
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    
    :deep(.arco-card-body) {
      padding: 20px;
    }
    
    :deep(.arco-form-item) {
      margin-bottom: 0;
      margin-right: 16px;
    }
    
    :deep(.arco-form-item-label) {
      font-weight: 500;
      color: #4e5969;
    }
    
    :deep(.arco-input),
    :deep(.arco-select) {
      width: 100%;
    }
  }
}

// 表格区域样式
:deep(.gi-table) {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  margin-bottom: 24px;
  max-height: calc(100vh - 300px);
  overflow: hidden;
  
  .arco-table-container {
    overflow-x: auto;
    overflow-y: auto;
    max-height: calc(100vh - 350px);
  }
  
  .arco-table {
    overflow: visible;
  }
  
  .arco-table-body {
    overflow-y: auto;
  }
}



.remark-content {
  max-width: 180px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #4e5969;
}

.no-remark {
  color: #c9cdd4;
  font-style: italic;
}

.member-form {
  .form-row {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 16px;
    margin-bottom: 16px;
  }

  .form-item {
    margin-bottom: 16px;

    label {
      display: block;
      font-weight: 500;
      color: #4e5969;
      margin-bottom: 6px;

      .required {
        color: #f53f3f;
      }
    }

    .arco-input,
    .arco-select,
    .arco-textarea,
    .arco-date-picker {
      width: 100%;
    }
  }
}

.status-form {
  .form-item {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 16px;

    label {
      font-weight: 500;
      color: #4e5969;
      min-width: 80px;
    }

    .arco-select {
      flex: 1;
    }
  }
}

.import-form {
  .form-item {
    margin-bottom: 16px;

    label {
      display: block;
      font-weight: 500;
      color: #4e5969;
      margin-bottom: 6px;
    }
  }
}

// 页面滚动修复
.construction-personnel-page {
  height: 100vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  
  :deep(.gi-page-layout) {
    height: 100%;
    overflow: hidden;
    display: flex;
    flex-direction: column;
  }
  
  :deep(.gi-page-layout-content) {
    flex: 1;
    overflow: hidden;
    display: flex;
    flex-direction: column;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;

    .header-actions {
      justify-content: center;
    }
  }

  .search-section {
    .search-card {
      :deep(.arco-form) {
        flex-direction: column;
        align-items: stretch;
      }
      
      :deep(.arco-form-item) {
        margin-right: 0;
        margin-bottom: 16px;
      }
    }
  }

  .member-form {
    .form-row {
      grid-template-columns: 1fr;
    }
  }
}
</style> 