import { Provide } from '@midwayjs/core';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { ProjectTaskEntity } from '../entity/task';
import { ProjectPhaseEntity } from '../entity/phase';
import { ProjectTaskDependencyEntity } from '../entity/task_dependency';

/**
 * 甘特图数据服务
 */
@Provide()
export class ProjectGanttService extends BaseService {
  @InjectEntityModel(ProjectTaskEntity)
  projectTaskEntity: Repository<ProjectTaskEntity>;

  @InjectEntityModel(ProjectPhaseEntity)
  projectPhaseEntity: Repository<ProjectPhaseEntity>;

  @InjectEntityModel(ProjectTaskDependencyEntity)
  projectTaskDependencyEntity: Repository<ProjectTaskDependencyEntity>;

  /**
   * 获取甘特图数据（DHTMLX Gantt 格式）
   */
  async ganttData(projectId: number) {
    const phases = await this.projectPhaseEntity.find({
      where: { projectId },
      order: { sortOrder: 'ASC' },
    });
    const tasks = await this.projectTaskEntity.find({
      where: { projectId },
      order: { sortOrder: 'ASC', createTime: 'ASC' },
    });
    const deps = await this.projectTaskDependencyEntity
      .createQueryBuilder('d')
      .where('d.taskId IN (:...taskIds)', {
        taskIds: tasks.length > 0 ? tasks.map(t => t.id) : [0],
      })
      .orWhere('d.dependsOnTaskId IN (:...depIds)', {
        depIds: tasks.length > 0 ? tasks.map(t => t.id) : [0],
      })
      .getMany();

    const data = [];

    for (const phase of phases) {
      data.push({
        id: `p_${phase.id}`,
        text: phase.name,
        start_date: phase.startDate || '',
        end_date: phase.endDate || '',
        progress: phase.progress / 100,
        type: 'project',
        open: true,
        sortOrder: phase.sortOrder,
        status: phase.status,
        phaseType: phase.type,
      });
    }

    for (const task of tasks) {
      let parent = '';
      if (task.parentId) {
        parent = `t_${task.parentId}`;
      } else if (task.phaseId) {
        parent = `p_${task.phaseId}`;
      }

      data.push({
        id: `t_${task.id}`,
        text: task.name,
        start_date: task.startDate || '',
        end_date: task.endDate || '',
        progress: task.progress / 100,
        parent,
        priority: task.priority,
        status: task.status,
        category: task.category,
        assignee: task.assigneeName,
        assigneeId: task.assigneeId,
        estimatedHours: task.estimatedHours,
        actualHours: task.actualHours,
        color: task.color,
        sortOrder: task.sortOrder,
      });
    }

    const links = deps.map(d => ({
      id: d.id,
      source: `t_${d.dependsOnTaskId}`,
      target: `t_${d.taskId}`,
      type: String(d.type),
    }));

    return { data, links };
  }

  /**
   * 甘特图拖拽批量更新
   */
  async ganttUpdate(
    items: { id: string; start_date: string; end_date: string; sortOrder?: number; parent?: string }[]
  ) {
    for (const item of items) {
      if (item.id.startsWith('p_')) {
        const phaseId = parseInt(item.id.replace('p_', ''));
        await this.projectPhaseEntity.update(phaseId, {
          startDate: item.start_date,
          endDate: item.end_date,
          ...(item.sortOrder !== undefined ? { sortOrder: item.sortOrder } : {}),
        });
      } else if (item.id.startsWith('t_')) {
        const taskId = parseInt(item.id.replace('t_', ''));
        const updateData: any = {
          startDate: item.start_date,
          endDate: item.end_date,
        };
        if (item.sortOrder !== undefined) {
          updateData.sortOrder = item.sortOrder;
        }
        if (item.parent) {
          if (item.parent.startsWith('p_')) {
            updateData.phaseId = parseInt(item.parent.replace('p_', ''));
            updateData.parentId = null;
          } else if (item.parent.startsWith('t_')) {
            updateData.parentId = parseInt(item.parent.replace('t_', ''));
          }
        }
        await this.projectTaskEntity.update(taskId, updateData);
      }
    }
  }
}
