<!--
  项目进度看板页面
  实现Kanban风格的项目管理界面
-->
<template>
  <div class="kanban-container">
    <!-- 顶部工具栏 -->
    <div class="kanban-header">
      <div class="header-left">
        <!-- 项目选择器 -->
        <div class="project-selector">
          <a-select
            v-model="selectedProject"
            placeholder="选择项目"
            style="width: 200px"
            @change="handleProjectChange"
          >
            <a-option
              v-for="project in projectList"
              :key="project.projectId"
              :value="project.projectId"
            >
              {{ project.projectName }}
            </a-option>
          </a-select>
          <a-button type="text" size="small">
            <template #icon><icon-search /></template>
          </a-button>
        </div>
        
        <!-- 项目进度 -->
        <div v-if="currentProject" class="project-progress">
          <span class="progress-label">项目进度</span>
          <a-progress
            :percent="projectProgress"
            :width="200"
            :stroke-width="8"
            color="rgb(var(--success-6))"
          />
          <span class="progress-percent">{{ projectProgress }}%</span>
        </div>
      </div>
      
      <div class="header-right">
        <a-input-search
          v-model="searchKeyword"
          placeholder="任务名称/负责人"
          style="width: 200px"
          @search="handleSearch"
        />
        <a-button>查看进度</a-button>
        <a-button @click="importTasks">导入任务</a-button>
        <a-button type="primary" @click="showAddTaskGroupModal">
          <template #icon><icon-plus /></template>
          新增任务组
        </a-button>
      </div>
    </div>
    
    <!-- 看板主体 -->
    <div class="kanban-board" v-if="currentProject">
      <div class="board-columns">
        <!-- 任务状态列 -->
        <div
          v-for="column in columns"
          :key="column.status"
          class="board-column"
          @drop="handleDrop($event, column.status)"
          @dragover="handleDragOver"
        >
          <div class="column-header">
            <div class="column-title">
              <span class="status-dot" :style="{ backgroundColor: column.color }"></span>
              <span class="title-text">{{ column.title }}</span>
              <span class="task-count">({{ getTaskCountByStatus(column.status) }})</span>
            </div>
            <a-dropdown>
              <a-button type="text" size="small">
                <template #icon><icon-more /></template>
              </a-button>
              <template #content>
                <a-doption @click="addTask(column.status)">
                  <template #icon><icon-plus /></template>
                  新增任务
                </a-doption>
              </template>
            </a-dropdown>
          </div>
          
          <div class="column-content">
            <!-- 新增任务按钮 -->
            <div class="add-task-btn" @click="addTask(column.status)">
              <icon-plus />
              新增任务
            </div>
            
            <!-- 任务卡片列表 -->
            <div
              v-for="task in getTasksByStatus(column.status)"
              :key="task.id"
              class="task-card"
              draggable="true"
              @dragstart="handleDragStart($event, task)"
              @click="viewTaskDetail(task)"
            >
              <div class="task-header">
                <h3 class="task-title">{{ task.taskName }}</h3>
                <a-dropdown>
                  <a-button type="text" size="mini">
                    <template #icon><icon-more /></template>
                  </a-button>
                  <template #content>
                    <a-doption @click="editTask(task)">
                      <template #icon><icon-edit /></template>
                      编辑
                    </a-doption>
                    <a-doption @click="deleteTask(task)" class="danger">
                      <template #icon><icon-delete /></template>
                      删除
                    </a-doption>
                  </template>
                </a-dropdown>
              </div>
              
              <div class="task-description">
                {{ task.description || '该任务暂无描述信息，项目进度跟踪管理任务。' }}
              </div>
              
              <div class="task-dates">
                <span v-if="task.taskPeriod">
                  {{ formatDate(task.taskPeriod[0]) }} - {{ formatDate(task.taskPeriod[1]) }}
                </span>
              </div>
              
                             <div class="task-priority">
                 <a-tag
                   :color="getPriorityColor((task as any).priority)"
                   size="small"
                 >
                   {{ getPriorityText((task as any).priority) }}
                 </a-tag>
               </div>
              
              <div class="task-footer">
                <div class="task-progress">
                  <span class="progress-text">{{ task.progress || 0 }}%</span>
                  <div class="progress-icons">
                    <icon-message />
                    <span>2</span>
                    <icon-thumb-up />
                    <span>16</span>
                    <icon-eye />
                    <span>7</span>
                  </div>
                </div>
                
                <div class="task-avatars">
                  <a-avatar-group :size="24" :max-count="3">
                    <a-avatar
                      v-for="member in getTaskMembers(task)"
                      :key="member.id"
                      :style="{ backgroundColor: member.color }"
                    >
                      {{ member.name.charAt(0) }}
                    </a-avatar>
                  </a-avatar-group>
                  <span v-if="getTaskMembers(task).length > 3" class="more-count">
                    +{{ getTaskMembers(task).length - 3 }}
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 空状态 -->
    <div v-else class="empty-state">
      <a-empty description="请选择项目查看任务进度" />
    </div>
    
    <!-- 添加任务组弹窗 -->
    <a-modal
      v-model:visible="addTaskGroupVisible"
      title="新增任务组"
      @ok="handleAddTaskGroup"
      @cancel="resetTaskGroupForm"
    >
      <a-form ref="taskGroupFormRef" :model="taskGroupForm">
        <a-form-item field="groupName" label="任务组名称" required>
          <a-input v-model="taskGroupForm.groupName" placeholder="请输入任务组名称" />
        </a-form-item>
        <a-form-item field="description" label="描述">
          <a-textarea v-model="taskGroupForm.description" placeholder="请输入任务组描述" />
        </a-form-item>
      </a-form>
    </a-modal>
    
    <!-- 添加/编辑任务弹窗 -->
    <TaskModal
      v-model:visible="taskModalVisible"
      :project-id="selectedProject"
      :initial-status="initialTaskStatus"
      :task-data="editingTask"
      @success="refreshTasks"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { Message } from '@arco-design/web-vue'
import { listProject, type ProjectResp } from '@/apis/project'
import { listTask, addTaskGroup, deleteTask as deleteTaskApi, updateTaskStatus } from '@/apis/project/task'
import type { TaskResp } from '@/apis/project/type'
import TaskModal from './components/TaskModal.vue'

// 项目相关数据
const projectList = ref<ProjectResp[]>([])
const selectedProject = ref<string>('')
const currentProject = computed(() => 
  projectList.value.find(p => p.projectId === selectedProject.value)
)

// 任务相关数据
const taskList = ref<TaskResp[]>([])
const searchKeyword = ref('')

// 看板列配置
const columns = [
  { status: 'planning', title: '计划中', color: '#ff7d00' },
  { status: 'inProgress', title: '正在做', color: '#165dff' },
  { status: 'review', title: '待复核', color: '#ffb400' },
  { status: 'completed', title: '已完成', color: '#00b42a' },
  { status: 'other', title: '其他', color: '#86909c' },
]

// 弹窗相关
const addTaskGroupVisible = ref(false)
const taskModalVisible = ref(false)
const initialTaskStatus = ref('')
const editingTask = ref<TaskResp | null>(null)

// 表单数据
const taskGroupForm = reactive({
  groupName: '',
  description: ''
})

// 计算项目进度
const projectProgress = computed(() => {
  if (!taskList.value.length) return 0
  const totalTasks = taskList.value.length
  const completedTasks = taskList.value.filter(task => task.status === 'completed').length
  return Math.round((completedTasks / totalTasks) * 100)
})

// 获取指定状态的任务
const getTasksByStatus = (status: string) => {
  return taskList.value.filter(task => task.status === status)
}

// 获取指定状态的任务数量
const getTaskCountByStatus = (status: string) => {
  return getTasksByStatus(status).length
}

// 获取任务成员
const getTaskMembers = (task: TaskResp) => {
  // 模拟团队成员数据
  const colors = ['#165dff', '#00b42a', '#ff7d00', '#f53f3f', '#722ed1']
  const members = task.participants || [task.responsiblePerson]
  return members.map((name, index) => ({
    id: index,
    name: name,
    color: colors[index % colors.length]
  }))
}

// 获取优先级颜色
const getPriorityColor = (priority: string) => {
  const priorityMap: Record<string, string> = {
    'high': 'red',
    'medium': 'orange', 
    'low': 'green'
  }
  return priorityMap[priority] || 'blue'
}

// 获取优先级文本
const getPriorityText = (priority: string) => {
  const priorityMap: Record<string, string> = {
    'high': '高优先级',
    'medium': '普通',
    'low': '低优先级'
  }
  return priorityMap[priority] || '普通'
}

// 拖拽相关
const draggedTask = ref<TaskResp | null>(null)

const handleDragStart = (e: DragEvent, task: TaskResp) => {
  draggedTask.value = task
  e.dataTransfer!.effectAllowed = 'move'
}

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

const handleDrop = async (e: DragEvent, newStatus: string) => {
  e.preventDefault()
  if (!draggedTask.value || draggedTask.value.status === newStatus) return
  
  try {
    // 更新任务状态
    await updateTaskStatus({ status: newStatus }, draggedTask.value.id)
    draggedTask.value.status = newStatus
    Message.success('任务状态更新成功')
  } catch (error) {
    Message.error('更新任务状态失败')
  }
  
  draggedTask.value = null
}

// 加载项目列表
const loadProjects = async () => {
  try {
    const { data } = await listProject({ page: 1, size: 100 })
    projectList.value = data.list || []
  } catch (error) {
    Message.error('加载项目列表失败')
  }
}

// 加载任务列表
const loadTasks = async () => {
  if (!selectedProject.value) return
  
  try {
    const { data } = await listTask({
      projectId: Number(selectedProject.value),
      page: 1,
      size: 100
    })
    taskList.value = data.list || []
  } catch (error) {
    Message.error('加载任务列表失败')
  }
}

// 项目切换
const handleProjectChange = () => {
  loadTasks()
}

// 搜索
const handleSearch = () => {
  loadTasks()
}

// 显示添加任务组弹窗
const showAddTaskGroupModal = () => {
  if (!selectedProject.value) {
    Message.warning('请先选择项目')
    return
  }
  addTaskGroupVisible.value = true
}

// 添加任务组
const handleAddTaskGroup = async () => {
  try {
    await addTaskGroup({
      ...taskGroupForm,
      projectId: Number(selectedProject.value)
    })
    Message.success('任务组添加成功')
    addTaskGroupVisible.value = false
    resetTaskGroupForm()
  } catch (error) {
    Message.error('添加任务组失败')
  }
}

// 重置任务组表单
const resetTaskGroupForm = () => {
  taskGroupForm.groupName = ''
  taskGroupForm.description = ''
}

// 添加任务
const addTask = (status: string) => {
  if (!selectedProject.value) {
    Message.warning('请先选择项目')
    return
  }
  initialTaskStatus.value = status
  editingTask.value = null
  taskModalVisible.value = true
}

// 编辑任务
const editTask = (task: TaskResp) => {
  editingTask.value = task
  taskModalVisible.value = true
}

// 查看任务详情
const viewTaskDetail = (task: TaskResp) => {
  editTask(task)
}

// 删除任务
const deleteTask = async (task: TaskResp) => {
  try {
    await deleteTaskApi(task.id)
    Message.success('任务删除成功')
    loadTasks()
  } catch (error) {
    Message.error('删除任务失败')
  }
}

// 导入任务
const importTasks = () => {
  Message.info('导入功能开发中...')
}

// 刷新任务列表
const refreshTasks = () => {
  loadTasks()
}

// 格式化日期
const formatDate = (date: string) => {
  return date ? new Date(date).toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' }) : ''
}

onMounted(() => {
  loadProjects()
})
</script>

<style scoped lang="scss">
.kanban-container {
  height: 100vh;
  background: #f7f8fa;
  display: flex;
  flex-direction: column;
}

.kanban-header {
  background: white;
  padding: 16px 24px;
  border-bottom: 1px solid var(--color-border-2);
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .header-left {
    display: flex;
    align-items: center;
    gap: 24px;
    
    .project-selector {
      display: flex;
      align-items: center;
      gap: 8px;
    }
    
    .project-progress {
      display: flex;
      align-items: center;
      gap: 12px;
      
      .progress-label {
        font-size: 14px;
        color: var(--color-text-2);
      }
      
      .progress-percent {
        font-size: 14px;
        font-weight: 500;
        color: var(--color-text-1);
      }
    }
  }
  
  .header-right {
    display: flex;
    align-items: center;
    gap: 12px;
  }
}

.kanban-board {
  flex: 1;
  padding: 16px 24px;
  overflow: hidden;
}

.board-columns {
  display: flex;
  gap: 16px;
  height: 100%;
}

.board-column {
  flex: 1;
  background: white;
  border-radius: 8px;
  border: 1px solid var(--color-border-2);
  display: flex;
  flex-direction: column;
  min-height: 0;
  
  .column-header {
    padding: 16px;
    border-bottom: 1px solid var(--color-border-2);
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .column-title {
      display: flex;
      align-items: center;
      gap: 8px;
      
      .status-dot {
        width: 8px;
        height: 8px;
        border-radius: 50%;
      }
      
      .title-text {
        font-size: 14px;
        font-weight: 500;
        color: var(--color-text-1);
      }
      
      .task-count {
        font-size: 12px;
        color: var(--color-text-3);
      }
    }
  }
  
  .column-content {
    flex: 1;
    padding: 16px;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
    gap: 12px;
  }
}

.add-task-btn {
  padding: 12px;
  border: 2px dashed var(--color-border-2);
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  color: var(--color-text-3);
  cursor: pointer;
  transition: all 0.2s;
  
  &:hover {
    border-color: var(--color-primary-6);
    color: var(--color-primary-6);
  }
}

.task-card {
  background: white;
  border: 1px solid var(--color-border-2);
  border-radius: 6px;
  padding: 12px;
  cursor: pointer;
  transition: all 0.2s;
  
  &:hover {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    transform: translateY(-1px);
  }
  
  .task-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 8px;
    
    .task-title {
      font-size: 14px;
      font-weight: 500;
      color: var(--color-text-1);
      margin: 0;
      line-height: 1.4;
    }
  }
  
  .task-description {
    font-size: 12px;
    color: var(--color-text-3);
    line-height: 1.4;
    margin-bottom: 12px;
  }
  
  .task-dates {
    font-size: 12px;
    color: var(--color-text-3);
    margin-bottom: 8px;
  }
  
  .task-priority {
    margin-bottom: 12px;
  }
  
  .task-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .task-progress {
      display: flex;
      align-items: center;
      gap: 8px;
      
      .progress-text {
        font-size: 12px;
        font-weight: 500;
        color: var(--color-text-2);
      }
      
      .progress-icons {
        display: flex;
        align-items: center;
        gap: 4px;
        font-size: 12px;
        color: var(--color-text-3);
      }
    }
    
    .task-avatars {
      display: flex;
      align-items: center;
      gap: 4px;
      
      .more-count {
        font-size: 12px;
        color: var(--color-text-3);
      }
    }
  }
}

.empty-state {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.danger {
  color: var(--color-danger-6) !important;
}
</style> 