import { Injectable } from '@angular/core';
import { FmodeParse } from 'fmode-ng/parse';

const Parse = FmodeParse.with('nova');

/**
 * 项目数据迁移服务
 * 用于批量更新现有项目的负责人信息
 */
@Injectable({
  providedIn: 'root'
})
export class ProjectMigrationService {
  
  /**
   * 批量更新项目负责人
   * 为所有没有assignee的项目设置组长为负责人
   */
  async migrateProjectAssignees(): Promise<{
    total: number;
    success: number;
    failed: number;
    details: any[];
  }> {
    const company = localStorage.getItem('company');
    if (!company) {
      console.error('❌ 未找到公司ID');
      return { total: 0, success: 0, failed: 0, details: [] };
    }

    try {
      console.log('🚀 开始迁移项目负责人数据...');
      
      // 1. 查询所有没有assignee或department的项目
      const projectQuery = new Parse.Query('Project');
      projectQuery.equalTo('company', company);
      projectQuery.notEqualTo('isDeleted', true);
      projectQuery.limit(1000);
      
      const projects = await projectQuery.find();
      console.log(`📊 找到 ${projects.length} 个项目`);

      const results = {
        total: projects.length,
        success: 0,
        failed: 0,
        details: [] as any[]
      };

      // 2. 遍历每个项目
      for (const project of projects) {
        const projectId = project.id;
        const projectTitle = project.get('title') || '未命名项目';
        const existingAssignee = project.get('assignee');
        const existingDepartment = project.get('department');

        try {
          // 如果已经有assignee，跳过
          if (existingAssignee) {
            console.log(`⏭️  项目 "${projectTitle}" 已有负责人，跳过`);
            results.details.push({
              projectId,
              title: projectTitle,
              status: 'skipped',
              reason: '已有负责人'
            });
            continue;
          }

          // 如果有department，使用其leader
          if (existingDepartment) {
            const dept = existingDepartment;
            await dept.fetch({ include: ['leader'] });
            const leader = dept.get('leader');
            
            if (leader) {
              project.set('assignee', leader);
              await project.save();
              results.success++;
              console.log(`✅ 项目 "${projectTitle}" 已设置负责人: ${leader.get('name')}`);
              results.details.push({
                projectId,
                title: projectTitle,
                status: 'success',
                assignee: leader.get('name')
              });
            } else {
              results.failed++;
              console.warn(`⚠️  项目 "${projectTitle}" 的项目组没有组长`);
              results.details.push({
                projectId,
                title: projectTitle,
                status: 'failed',
                reason: '项目组没有组长'
              });
            }
            continue;
          }

          // 如果既没有assignee也没有department，尝试查找默认项目组
          console.log(`🔍 项目 "${projectTitle}" 没有项目组，尝试查找默认项目组...`);
          
          // 查找第一个项目组
          const deptQuery = new Parse.Query('Department');
          deptQuery.equalTo('company', company);
          deptQuery.equalTo('type', 'project');
          deptQuery.notEqualTo('isDeleted', true);
          deptQuery.include('leader');
          deptQuery.ascending('createdAt');
          deptQuery.limit(1);
          
          const defaultDept = await deptQuery.first();
          
          if (defaultDept) {
            const leader = defaultDept.get('leader');
            if (leader) {
              project.set('department', defaultDept);
              project.set('assignee', leader);
              await project.save();
              results.success++;
              console.log(`✅ 项目 "${projectTitle}" 已分配到默认项目组，负责人: ${leader.get('name')}`);
              results.details.push({
                projectId,
                title: projectTitle,
                status: 'success',
                assignee: leader.get('name'),
                department: defaultDept.get('name')
              });
            } else {
              results.failed++;
              console.warn(`⚠️  默认项目组没有组长`);
              results.details.push({
                projectId,
                title: projectTitle,
                status: 'failed',
                reason: '默认项目组没有组长'
              });
            }
          } else {
            results.failed++;
            console.warn(`⚠️  项目 "${projectTitle}" 无法找到项目组`);
            results.details.push({
              projectId,
              title: projectTitle,
              status: 'failed',
              reason: '没有可用的项目组'
            });
          }

        } catch (error) {
          results.failed++;
          console.error(`❌ 更新项目 "${projectTitle}" 失败:`, error);
          results.details.push({
            projectId,
            title: projectTitle,
            status: 'error',
            error: (error as Error).message
          });
        }
      }

      console.log('🎉 迁移完成！');
      console.log(`📊 总计: ${results.total}, 成功: ${results.success}, 失败: ${results.failed}`);
      
      return results;

    } catch (error) {
      console.error('❌ 迁移失败:', error);
      throw error;
    }
  }

  /**
   * 为单个项目设置负责人
   */
  async setProjectAssignee(projectId: string, assigneeId: string): Promise<boolean> {
    try {
      const projectQuery = new Parse.Query('Project');
      const project = await projectQuery.get(projectId);
      
      const assigneeQuery = new Parse.Query('Profile');
      const assignee = await assigneeQuery.get(assigneeId);
      
      project.set('assignee', assignee);
      await project.save();
      
      console.log('✅ 项目负责人设置成功');
      return true;
    } catch (error) {
      console.error('❌ 设置项目负责人失败:', error);
      return false;
    }
  }

  /**
   * 检查项目数据状态
   */
  async checkProjectsStatus(): Promise<{
    total: number;
    hasAssignee: number;
    hasDepartment: number;
    needsMigration: number;
  }> {
    const company = localStorage.getItem('company');
    if (!company) {
      console.error('❌ 未找到公司ID');
      return { total: 0, hasAssignee: 0, hasDepartment: 0, needsMigration: 0 };
    }

    try {
      const projectQuery = new Parse.Query('Project');
      projectQuery.equalTo('company', company);
      projectQuery.notEqualTo('isDeleted', true);
      projectQuery.include('assignee');
      projectQuery.include('department');
      projectQuery.limit(1000);
      
      const projects = await projectQuery.find();
      
      let hasAssignee = 0;
      let hasDepartment = 0;
      let needsMigration = 0;
      
      projects.forEach(project => {
        if (project.get('assignee')) hasAssignee++;
        if (project.get('department')) hasDepartment++;
        if (!project.get('assignee')) needsMigration++;
      });
      
      const status = {
        total: projects.length,
        hasAssignee,
        hasDepartment,
        needsMigration
      };
      
      console.log('📊 项目状态检查:', status);
      return status;
      
    } catch (error) {
      console.error('❌ 检查失败:', error);
      throw error;
    }
  }
}


