<template>
  <GiPageLayout>
    <a-card class="general-card" title="项目进度">
      <template #extra>
        <div class="flex items-center gap-2">
          <a-input placeholder="任务名称/负责人" allow-clear v-model="searchForm.keyword" @press-enter="search" />
          <a-button v-permission="['project:task:create']" type="primary" @click="openAddTaskModal">
            <template #icon><icon-plus /></template>
            <template #default>新增任务</template>
          </a-button>
          <a-button v-permission="['project:task:group:create']" @click="openAddTaskGroupModal">
            <template #icon><icon-plus /></template>
            <template #default>新增任务组</template>
          </a-button>
          <a-button v-permission="['project:task:import']" @click="openImportModal">
            <template #icon><icon-upload /></template>
            <template #default>导入任务</template>
          </a-button>
        </div>
      </template>

      <div class="project-info mb-6">
        <div class="project-progress">
          <div class="progress-title flex items-center justify-between">
            <div class="text-lg font-bold">项目进度：{{ currentProgress }}%</div>
            <div>
              <a-select v-model="selectedProject" placeholder="请选择项目" style="width: 240px" @change="handleProjectChange">
                <a-option v-for="project in projectList" :key="project.id" :value="project.id">{{ project.projectName }}</a-option>
              </a-select>
            </div>
          </div>
          <a-progress :percent="currentProgress" />

          <div class="mt-4 grid grid-cols-4 gap-4">
            <a-card class="status-card">
              <div class="card-title">全部任务</div>
              <div class="card-count">{{ taskStats.total }}</div>
            </a-card>
            <a-card class="status-card">
              <div class="card-title">已完成任务</div>
              <div class="card-count text-success">{{ taskStats.completed }}</div>
            </a-card>
            <a-card class="status-card">
              <div class="card-title">进行中任务</div>
              <div class="card-count text-warning">{{ taskStats.inProgress }}</div>
            </a-card>
            <a-card class="status-card">
              <div class="card-title">计划中任务</div>
              <div class="card-count text-info">{{ taskStats.planned }}</div>
            </a-card>
          </div>
        </div>
      </div>

      <div class="task-board">
        <a-row :gutter="16" class="task-container">
          <a-col :span="24">
            <div class="task-column">
              <div class="task-column-header bg-gray-100">
                <span class="column-title">所有任务</span>
                <a-tag>{{ taskStats.total }}</a-tag>
              </div>
              
              <div class="task-list">
                <div 
                  v-for="task in getAllTasks()" 
                  :key="task.id" 
                  class="task-card"
                  @click="openTaskDetail(task)"
                >
                  <div class="flex justify-between items-center">
                    <div class="task-card-title">{{ task.taskName }}</div>
                    <a-tag :color="getStatusColor(task.status)">{{ task.status }}</a-tag>
                  </div>
                  <div class="task-card-desc text-gray-500 text-xs mt-1">{{ task.description || '暂无描述' }}</div>
                  <div class="task-card-footer flex items-center justify-between mt-2">
                    <div class="flex items-center">
                      <icon-calendar class="mr-1 text-gray-500" />
                      <span class="text-xs">{{ formatDate(task.taskPeriod?.[0]) }} - {{ formatDate(task.taskPeriod?.[1]) }}</span>
                    </div>
                    <div class="text-xs">
                      <a-progress :percent="task.progress" size="small" />
                    </div>
                  </div>
                  <div class="task-card-members mt-2">
                    <a-avatar :size="24" v-for="(user, idx) in task.participants?.slice(0, 3)" :key="idx">{{ user.substring(0, 1) }}</a-avatar>
                    <a-avatar :size="24" v-if="task.participants?.length > 3">+{{ task.participants.length - 3 }}</a-avatar>
                  </div>
                </div>
                
                <div class="add-task-placeholder" @click="openAddTaskModal">
                  <icon-plus />
                  <span>添加任务</span>
                </div>
              </div>
            </div>
          </a-col>
        </a-row>
      </div>
    </a-card>

    <!-- 新增任务弹窗 -->
    <a-modal
      v-model:visible="addTaskModalVisible"
      :title="isEditTask ? '编辑任务' : '新增任务'"
      @cancel="resetTaskForm"
      @before-ok="handleTaskSubmit"
    >
      <a-form ref="taskFormRef" :model="taskForm" label-position="left" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }">
        <a-form-item field="taskName" label="任务名称" required>
          <a-input v-model="taskForm.taskName" placeholder="请输入" />
        </a-form-item>
        <a-form-item field="taskCode" label="任务编号" required>
          <a-input v-model="taskForm.taskCode" placeholder="请输入" />
        </a-form-item>
        <a-form-item field="projectId" label="所属项目" required>
          <a-select v-model="taskForm.projectId" placeholder="请选择">
            <a-option v-for="project in projectList" :key="project.id" :value="project.id">{{ project.projectName }}</a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="responsiblePerson" label="负责人" required>
          <a-select v-model="taskForm.responsiblePerson" placeholder="请选择">
            <a-option value="请选择">请选择</a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="participants" label="参与人">
          <a-select v-model="taskForm.participants" multiple placeholder="请选择">
            <a-option value="全部员工">全部员工</a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="taskPeriod" label="任务计划周期" required>
          <a-range-picker v-model="taskForm.taskPeriod" style="width: 100%" />
        </a-form-item>
        <a-form-item field="plannedHours" label="计划工时" required>
          <a-input-number v-model="taskForm.plannedHours" style="width: 100%" />
        </a-form-item>
        <a-form-item field="description" label="备注说明">
          <a-textarea v-model="taskForm.description" placeholder="请输入" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 新增任务组弹窗 -->
    <a-modal
      v-model:visible="addTaskGroupModalVisible"
      title="新增任务组"
      @cancel="resetTaskGroupForm"
      @before-ok="handleTaskGroupSubmit"
    >
      <a-form ref="taskGroupFormRef" :model="taskGroupForm" label-position="left" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }">
        <a-form-item field="groupName" label="组名称" required>
          <a-input v-model="taskGroupForm.groupName" placeholder="请输入" />
        </a-form-item>
        <a-form-item field="projectId" label="所属项目" required>
          <a-select v-model="taskGroupForm.projectId" placeholder="请选择">
            <a-option v-for="project in projectList" :key="project.id" :value="project.id">{{ project.projectName }}</a-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 任务详情弹窗 -->
    <a-modal
      v-model:visible="taskDetailModalVisible"
      title="任务详情"
      @cancel="closeTaskDetail"
    >
      <div v-if="currentTask">
        <a-descriptions :data="taskDetailInfos" layout="horizontal" bordered />
        
        <div class="mt-4">
          <h4>任务进度</h4>
          <a-progress :percent="currentTask.progress || 0" />
          
          <a-form class="mt-4">
            <a-form-item label="更新进度">
              <a-input-number v-model="updateProgress" :min="0" :max="100" style="width: 100%" />
            </a-form-item>
            <div class="flex justify-between">
              <a-button type="primary" @click="submitProgressUpdate">更新进度</a-button>
              <div>
                <a-button type="outline" class="mr-2" @click="openEditTask">
                  <template #icon><icon-edit /></template>编辑任务
                </a-button>
                <a-popconfirm content="是否确定删除?" @ok="deleteTask">
                  <a-button status="danger">
                    <template #icon><icon-delete /></template>删除任务
                  </a-button>
                </a-popconfirm>
              </div>
            </div>
          </a-form>
        </div>
      </div>
    </a-modal>

    <!-- 导入任务弹窗 -->
    <a-modal
      v-model:visible="importModalVisible"
      title="导入任务"
      @cancel="handleCancelImport"
      @before-ok="handleImport"
    >
      <div class="flex flex-col items-center justify-center p-8">
        <div class="text-primary text-4xl mb-4">
          <icon-file-upload />
        </div>
        <div class="text-lg font-medium mb-2">批量导入任务</div>
        <div class="text-gray-500 mb-4">拖动文件到此处，或点击下方按钮上传</div>
        <a-upload
          :file-list="fileList"
          :limit="1"
          @change="handleFileChange"
        >
          <template #upload-button>
            <a-button type="primary">选择文件</a-button>
          </template>
        </a-upload>
        
        <a-form class="w-full mt-4">
          <a-form-item field="projectId" label="导入至项目">
            <a-select v-model="importForm.projectId" placeholder="请选择项目">
              <a-option v-for="project in projectList" :key="project.id" :value="project.id">{{ project.projectName }}</a-option>
            </a-select>
          </a-form-item>
        </a-form>
      </div>
    </a-modal>
  </GiPageLayout>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { Message } from '@arco-design/web-vue'
import { listProject } from '@/apis/project'
import { listTask, addTask, addTaskGroup, updateTaskProgress, deleteTask as apiDeleteTask } from '@/apis/project/task'
import dayjs from 'dayjs'
import type { ProjectResp } from '@/apis/project/type'
import type { TaskResp } from '@/apis/project/type'

defineOptions({ name: 'ProjectTask' })

const taskFormRef = ref()
const taskGroupFormRef = ref()
const loading = ref(false)
const addTaskModalVisible = ref(false)
const addTaskGroupModalVisible = ref(false)
const taskDetailModalVisible = ref(false)
const importModalVisible = ref(false)
const currentTask = ref<TaskResp | null>(null)
const updateProgress = ref(0)
const initialTaskStatus = ref('')
const projectList = ref<ProjectResp[]>([])
const selectedProject = ref<number | null>(null)
const fileList = ref([])
const isEditTask = ref(false)

let searchForm = reactive({
  keyword: '',
})

const importForm = reactive({
  projectId: null as number | null,
})

// 任务看板列
const taskColumns = ref([
  { title: '计划中', status: '计划中', tasks: [] as TaskResp[] },
  { title: '正在做', status: '正在做', tasks: [] as TaskResp[] },
  { title: '待复核', status: '待复核', tasks: [] as TaskResp[] },
  { title: '已完成', status: '已完成', tasks: [] as TaskResp[] },
  { title: '其他', status: '其他', tasks: [] as TaskResp[] }
])

const taskForm = reactive({
  taskName: '',
  taskCode: '',
  projectId: null as number | null,
  responsiblePerson: '',
  participants: [] as string[],
  taskPeriod: [] as string[],
  plannedHours: 1,
  status: '',
  description: ''
})

const taskGroupForm = reactive({
  groupName: '',
  projectId: null as number | null
})

const taskStats = reactive({
  total: 0,
  completed: 0,
  inProgress: 0,
  planned: 0
})

const currentProgress = computed(() => {
  if (taskStats.total === 0) return 0
  return Math.round((taskStats.completed / taskStats.total) * 100)
})

const taskDetailInfos = computed(() => {
  if (!currentTask.value) return []
  
  return [
    { label: '任务名称', value: currentTask.value.taskName },
    { label: '任务编号', value: currentTask.value.taskCode },
    { label: '负责人', value: currentTask.value.responsiblePerson },
    { label: '参与人', value: currentTask.value.participants?.join(', ') },
    { label: '任务周期', value: currentTask.value.taskPeriod ? `${formatDate(currentTask.value.taskPeriod[0])} 至 ${formatDate(currentTask.value.taskPeriod[1])}` : '' },
    { label: '计划工时', value: `${currentTask.value.plannedHours || 0} 小时` },
    { label: '状态', value: currentTask.value.status },
    { label: '描述', value: currentTask.value.description || '无' }
  ]
})

const getTaskColumnHeaderClass = (status: string) => {
  switch (status) {
    case '计划中':
      return 'bg-gray-100'
    case '正在做':
      return 'bg-blue-50'
    case '待复核':
      return 'bg-orange-50'
    case '已完成':
      return 'bg-green-50'
    default:
      return 'bg-gray-50'
  }
}

const getStatusColor = (status: string) => {
  switch (status) {
    case '计划中':
      return 'blue'
    case '正在做':
      return 'orange'
    case '待复核':
      return 'purple'
    case '已完成':
      return 'green'
    default:
      return 'gray'
  }
}

const getAllTasks = () => {
  return taskColumns.value.flatMap(column => column.tasks)
}

const formatDate = (date: string) => {
  if (!date) return ''
  return dayjs(date).format('YYYY-MM-DD')
}

const fetchProjects = async () => {
  try {
    const res = await listProject({ page: 1, size: 100 })
    projectList.value = res.data?.list || []
    if (projectList.value.length > 0 && !selectedProject.value) {
      selectedProject.value = projectList.value[0].id
      await fetchTaskData()
    }
  } catch (error) {
    console.error(error)
    Message.error('获取项目列表失败')
  }
}

const fetchTaskData = async () => {
  if (!selectedProject.value) return
  
  loading.value = true
  try {
    const res = await listTask({ 
      projectId: selectedProject.value,
      page: 1,
      size: 100
    })
    
    // 重置任务列表
    taskColumns.value.forEach(column => {
      column.tasks = []
    })
    
    const tasks = res.data?.list || []
    
    // 计算统计数据
    taskStats.total = tasks.length
    taskStats.completed = tasks.filter(task => task.status === '已完成').length
    taskStats.inProgress = tasks.filter(task => task.status === '正在做').length
    taskStats.planned = tasks.filter(task => task.status === '计划中').length
    
    // 分配任务到对应的列
    tasks.forEach((task: TaskResp) => {
      const column = taskColumns.value.find(col => col.status === task.status)
      if (column) {
        column.tasks.push(task)
      } else {
        taskColumns.value.find(col => col.status === '其他')?.tasks.push(task)
      }
    })
  } catch (error) {
    console.error(error)
    Message.error('获取任务数据失败')
  } finally {
    loading.value = false
  }
}

const handleProjectChange = async (projectId: number) => {
  selectedProject.value = projectId
  await fetchTaskData()
  
  if (taskForm.projectId === null) {
    taskForm.projectId = projectId
  }
  
  if (taskGroupForm.projectId === null) {
    taskGroupForm.projectId = projectId
  }
  
  if (importForm.projectId === null) {
    importForm.projectId = projectId
  }
}

const search = () => {
  fetchTaskData()
}

const handleFileChange = (files: any) => {
  fileList.value = files
}

const resetTaskForm = () => {
  taskFormRef.value?.resetFields()
  taskForm.status = initialTaskStatus.value
  isEditTask.value = false
}

const resetTaskGroupForm = () => {
  taskGroupFormRef.value?.resetFields()
}

const openAddTaskModal = () => {
  resetTaskForm()
  initialTaskStatus.value = '计划中'
  taskForm.status = '计划中'
  taskForm.projectId = selectedProject.value
  addTaskModalVisible.value = true
}

const handleAddTaskPlaceholder = (status: string) => {
  resetTaskForm()
  initialTaskStatus.value = status
  taskForm.status = status
  taskForm.projectId = selectedProject.value
  addTaskModalVisible.value = true
}

const openAddTaskGroupModal = () => {
  taskGroupForm.projectId = selectedProject.value
  addTaskGroupModalVisible.value = true
}

const handleTaskSubmit = async () => {
  const valid = await taskFormRef.value?.validate()
  if (!valid) return false

  try {
    if (isEditTask.value && currentTask.value) {
      // 编辑任务的API调用
      Message.success('更新任务成功')
    } else {
      await addTask(taskForm)
      Message.success('添加任务成功')
    }
    fetchTaskData()
    return true
  } catch (error) {
    console.error(error)
    Message.error('操作失败')
    return false
  }
}

const handleTaskGroupSubmit = async () => {
  const valid = await taskGroupFormRef.value?.validate()
  if (!valid) return false

  try {
    await addTaskGroup(taskGroupForm)
    Message.success('添加任务组成功')
    return true
  } catch (error) {
    console.error(error)
    Message.error('添加任务组失败')
    return false
  }
}

const openTaskDetail = (task: TaskResp) => {
  currentTask.value = task
  updateProgress.value = task.progress || 0
  taskDetailModalVisible.value = true
}

const closeTaskDetail = () => {
  currentTask.value = null
  updateProgress.value = 0
  taskDetailModalVisible.value = false
}

const openEditTask = () => {
  if (!currentTask.value) return
  
  // 将当前任务数据填充到表单中
  Object.keys(taskForm).forEach(key => {
    if (currentTask.value && key in currentTask.value) {
      const taskKey = key as keyof typeof taskForm
      const currentTaskKey = key as keyof TaskResp
      
      if (taskKey === 'projectId' && typeof currentTask.value.projectId === 'number') {
        taskForm.projectId = currentTask.value.projectId
      } else if (taskKey === 'participants' && Array.isArray(currentTask.value.participants)) {
        taskForm.participants = [...currentTask.value.participants]
      } else if (taskKey === 'taskPeriod' && Array.isArray(currentTask.value.taskPeriod)) {
        taskForm.taskPeriod = [...currentTask.value.taskPeriod]
      } else if (['taskName', 'taskCode', 'responsiblePerson', 'status', 'description'].includes(taskKey)) {
        // @ts-ignore: Handling string properties safely
        taskForm[taskKey] = currentTask.value[currentTaskKey] as any
      } else if (taskKey === 'plannedHours' && typeof currentTask.value.plannedHours === 'number') {
        taskForm.plannedHours = currentTask.value.plannedHours
      }
    }
  })
  
  // 关闭详情弹窗，打开编辑弹窗
  taskDetailModalVisible.value = false
  addTaskModalVisible.value = true
  isEditTask.value = true
}

const submitProgressUpdate = async () => {
  if (!currentTask.value) return

  try {
    await updateTaskProgress({ progress: updateProgress.value }, currentTask.value.id)
    Message.success('更新进度成功')
    
    // 更新本地数据
    currentTask.value.progress = updateProgress.value
    
    // 刷新任务列表
    await fetchTaskData()
  } catch (error) {
    console.error(error)
    Message.error('更新进度失败')
  }
}

const deleteTask = async () => {
  if (!currentTask.value) return
  
  try {
    await apiDeleteTask(currentTask.value.id)
    Message.success('删除任务成功')
    
    // 关闭详情弹窗
    closeTaskDetail()
    
    // 刷新任务列表
    await fetchTaskData()
  } catch (error) {
    console.error(error)
    Message.error('删除任务失败')
  }
}

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

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

const handleImport = () => {
  if (fileList.value.length === 0) {
    Message.warning('请选择文件')
    return false
  }
  
  if (!importForm.projectId) {
    Message.warning('请选择导入目标项目')
    return false
  }
  
  // 调用导入API
  Message.success('导入成功')
  handleCancelImport()
  return true
}

watch(() => selectedProject.value, async (newVal) => {
  if (newVal) {
    await fetchTaskData()
  }
})

onMounted(async () => {
  await fetchProjects()
})
</script>

<style scoped>
.task-board-container {
  padding: 16px;
}
.project-info {
  padding: 16px 0;
}
.progress-title {
  margin-bottom: 12px;
}
.status-card {
  text-align: center;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
}
.card-title {
  font-size: 14px;
  color: #7f7f7f;
}
.card-count {
  font-size: 28px;
  font-weight: bold;
  margin-top: 8px;
}
.text-success {
  color: #00b42a;
}
.text-warning {
  color: #ff7d00;
}
.text-info {
  color: #0fbbd0;
}
.task-container {
  overflow-x: auto;
  min-height: 600px;
}
.task-column {
  background-color: #f5f5f5;
  border-radius: 4px;
  height: 100%;
  min-height: 600px;
}
.task-column-header {
  padding: 12px;
  border-radius: 4px 4px 0 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
}
.task-list {
  padding: 8px;
}
.task-card {
  background-color: white;
  border-radius: 4px;
  padding: 12px;
  margin-bottom: 8px;
  cursor: pointer;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: box-shadow 0.3s;
}
.task-card:hover {
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.2);
}
.task-card-title {
  font-weight: bold;
}
.task-card-members {
  display: flex;
  gap: 4px;
}
.add-task-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 12px;
  background-color: #e8e8e8;
  border-radius: 4px;
  color: #7f7f7f;
  cursor: pointer;
  gap: 8px;
}
.add-task-placeholder:hover {
  background-color: #d9d9d9;
}
</style> 