/**
 * 项目列表数据测试脚本
 * 
 * 用途：在浏览器控制台中运行，测试Parse Server项目数据查询
 * 
 * 使用方法：
 * 1. 打开浏览器开发者工具（F12）
 * 2. 切换到Console标签
 * 3. 复制并粘贴此脚本
 * 4. 按回车运行
 */

(async function testProjectListData() {
  console.log('🔍 开始测试项目列表数据加载...\n');
  
  // 1. 检查localStorage中的公司ID
  const companyId = localStorage.getItem('company');
  console.log('📊 步骤1: 检查公司ID');
  console.log('  公司ID:', companyId || '❌ 未找到');
  
  if (!companyId) {
    console.error('❌ 错误: localStorage中没有company字段');
    console.log('💡 解决方法: 请先登录或手动设置公司ID');
    console.log('   示例: localStorage.setItem("company", "your-company-id")');
    return;
  }
  
  // 2. 检查Parse是否可用
  console.log('\n📊 步骤2: 检查Parse SDK');
  if (typeof Parse === 'undefined') {
    console.error('❌ 错误: Parse SDK未加载');
    console.log('💡 解决方法: 请确保在项目页面中运行此脚本');
    return;
  }
  console.log('  ✅ Parse SDK已加载');
  
  // 3. 查询项目数据
  console.log('\n📊 步骤3: 查询项目数据');
  try {
    const ProjectQuery = new Parse.Query('Project');
    
    // 设置查询条件
    ProjectQuery.equalTo('company', {
      __type: 'Pointer',
      className: 'Company',
      objectId: companyId
    });
    ProjectQuery.notEqualTo('isDeleted', true);
    ProjectQuery.include('contact', 'assignee', 'owner');
    ProjectQuery.descending('updatedAt');
    ProjectQuery.limit(100);
    
    console.log('  查询条件:');
    console.log('    - company:', companyId);
    console.log('    - isDeleted: != true');
    console.log('    - include: contact, assignee, owner');
    console.log('    - limit: 100');
    console.log('  正在查询...');
    
    const projects = await ProjectQuery.find();
    
    console.log(`\n✅ 查询成功! 找到 ${projects.length} 个项目\n`);
    
    if (projects.length === 0) {
      console.warn('⚠️ 数据库中没有符合条件的项目');
      console.log('💡 可能的原因:');
      console.log('  1. Project表中没有数据');
      console.log('  2. 项目的company字段不匹配当前公司ID');
      console.log('  3. 所有项目的isDeleted字段都为true');
      return;
    }
    
    // 4. 分析项目数据
    console.log('📊 步骤4: 分析项目数据\n');
    
    const statusCount = {};
    const stageCount = {};
    const assignedCount = { assigned: 0, unassigned: 0 };
    
    projects.forEach(project => {
      // 统计状态
      const status = project.get('status') || '未知';
      statusCount[status] = (statusCount[status] || 0) + 1;
      
      // 统计阶段
      const stage = project.get('currentStage') || '未知';
      stageCount[stage] = (stageCount[stage] || 0) + 1;
      
      // 统计分配情况
      const assignee = project.get('assignee');
      if (assignee && assignee.id) {
        assignedCount.assigned++;
      } else {
        assignedCount.unassigned++;
      }
    });
    
    console.log('📈 项目状态分布:');
    Object.entries(statusCount).forEach(([status, count]) => {
      console.log(`  ${status}: ${count}个`);
    });
    
    console.log('\n📈 项目阶段分布:');
    Object.entries(stageCount).forEach(([stage, count]) => {
      console.log(`  ${stage}: ${count}个`);
    });
    
    console.log('\n📈 分配情况:');
    console.log(`  已分配: ${assignedCount.assigned}个`);
    console.log(`  未分配: ${assignedCount.unassigned}个`);
    
    // 5. 显示前3个项目的详细信息
    console.log('\n📋 前3个项目详情:\n');
    projects.slice(0, 3).forEach((project, index) => {
      const contact = project.get('contact');
      const assignee = project.get('assignee');
      
      console.log(`${index + 1}. ${project.get('title') || '未命名项目'}`);
      console.log(`   ID: ${project.id}`);
      console.log(`   客户: ${contact?.get('name') || '未知'}`);
      console.log(`   负责人: ${assignee?.get('name') || '未分配'}`);
      console.log(`   状态: ${project.get('status') || '未知'}`);
      console.log(`   阶段: ${project.get('currentStage') || '未知'}`);
      console.log(`   更新时间: ${project.get('updatedAt')?.toLocaleString() || '未知'}`);
      console.log('');
    });
    
    // 6. 看板分组预览
    console.log('📊 看板分组预览:\n');
    
    const orderAssignment = projects.filter(p => {
      const assignee = p.get('assignee');
      return !assignee || !assignee.id || p.get('currentStage') === '订单分配';
    });
    
    const requirements = projects.filter(p => {
      const stage = p.get('currentStage');
      const status = p.get('status');
      const assignee = p.get('assignee');
      const isAftercare = status === '已完成' || ['投诉处理', '客户评价'].includes(stage);
      const isOrder = !assignee || !assignee.id || stage === '订单分配';
      return !isAftercare && !isOrder && ['需求沟通', '方案确认'].includes(stage);
    });
    
    const delivery = projects.filter(p => {
      const stage = p.get('currentStage');
      const status = p.get('status');
      const assignee = p.get('assignee');
      const isAftercare = status === '已完成' || ['投诉处理', '客户评价'].includes(stage);
      const isOrder = !assignee || !assignee.id || stage === '订单分配';
      return !isAftercare && !isOrder && ['建模', '软装', '渲染', '后期', '尾款结算'].includes(stage);
    });
    
    const aftercare = projects.filter(p => {
      const stage = p.get('currentStage');
      const status = p.get('status');
      return status === '已完成' || ['投诉处理', '客户评价'].includes(stage);
    });
    
    console.log(`  订单分配: ${orderAssignment.length}个项目`);
    console.log(`  确认需求: ${requirements.length}个项目`);
    console.log(`  交付执行: ${delivery.length}个项目`);
    console.log(`  售后: ${aftercare.length}个项目`);
    
    console.log('\n✅ 测试完成! 数据加载正常\n');
    console.log('💡 提示: 如果页面上没有显示数据，请检查:');
    console.log('  1. 浏览器控制台是否有错误信息');
    console.log('  2. 网络请求是否成功（Network标签）');
    console.log('  3. 页面是否正确初始化（刷新页面试试）');
    
  } catch (error) {
    console.error('❌ 查询失败:', error);
    console.log('\n💡 可能的原因:');
    console.log('  1. Parse Server连接失败');
    console.log('  2. 权限不足');
    console.log('  3. 查询语法错误');
    console.log('\n详细错误信息:', error.message);
  }
})();

