import { postgrestGet, type PostgrestParams } from '../postgrest-client';

/**
 * 评查点分组接口
 */
export interface RuleGroup {
  id: string;
  pid: string;
  name: string;
  status: boolean;
  ruleCount?: number;  // 评查点数量
  children?: RuleGroup[];  // 子分组
}

/**
 * 获取评查点分组列表
 * @returns 评查点分组列表
 */
export async function getRuleGroups(): Promise<{data: RuleGroup[]; error?: never} | {data?: never; error: string; status?: number}> {
  try {
    // 1. 获取所有一级分组（pid=0）
    const parentGroupsParams: PostgrestParams = {
      select: `
        id,
        pid,
        name,
        status
      `,
      filter: {
        'pid': 'eq.0'
      }
    };
    
    const parentGroupsResponse = await postgrestGet<{code: number; msg: string; data: Array<{
      id: number;
      pid: number;
      name: string;
      status: boolean;
    }>}>('evaluation_point_groups', parentGroupsParams);
    
    if (parentGroupsResponse.error) {
      return { error: parentGroupsResponse.error, status: parentGroupsResponse.status };
    }
    
    // 处理响应数据
    let parentGroups: RuleGroup[] = [];
    if (parentGroupsResponse.data && 'code' in parentGroupsResponse.data && parentGroupsResponse.data.data) {
      parentGroups = parentGroupsResponse.data.data.map(group => ({
        id: group.id.toString(),
        pid: group.pid.toString(),
        name: group.name,
        status: group.status,
        children: [] // 初始化子分组数组
      }));
    } else if (Array.isArray(parentGroupsResponse.data)) {
      parentGroups = parentGroupsResponse.data.map(group => ({
        id: group.id.toString(),
        pid: group.pid.toString(),
        name: group.name,
        status: group.status,
        children: [] // 初始化子分组数组
      }));
    }
    
    return { data: parentGroups };
  } catch (error) {
    console.error('获取评查点分组列表出错:', error);
    return { 
      error: error instanceof Error ? error.message : '获取评查点分组列表失败',
      status: 500
    };
  }
}

/**
 * 获取指定分组的子分组
 * @param parentId 父分组ID
 * @returns 子分组列表
 */
export async function getChildGroups(parentId: string): Promise<{data: RuleGroup[]; error?: never} | {data?: never; error: string; status?: number}> {
  try {
    // 1. 获取子分组
    const childGroupsParams: PostgrestParams = {
      select: `
        id,
        pid,
        name,
        status
      `,
      filter: {
        'pid': `eq.${parentId}`
      }
    };
    
    const childGroupsResponse = await postgrestGet<{code: number; msg: string; data: Array<{
      id: number;
      pid: number;
      name: string;
      status: boolean;
    }>}>('evaluation_point_groups', childGroupsParams);
    
    if (childGroupsResponse.error) {
      return { error: childGroupsResponse.error, status: childGroupsResponse.status };
    }
    
    // 2. 获取每个子分组的评查点数量
    let childGroups: RuleGroup[] = [];
    if (childGroupsResponse.data && 'code' in childGroupsResponse.data && childGroupsResponse.data.data) {
      childGroups = await Promise.all(childGroupsResponse.data.data.map(async group => {
        // 获取该分组的评查点数量
        const ruleCountParams: PostgrestParams = {
          select: 'id',
          filter: {
            'evaluation_point_groups_id': `eq.${group.id}`
          }
        };
        
        const ruleCountResponse = await postgrestGet<{code: number; msg: string; data: Array<{id: number}>}>('evaluation_points', ruleCountParams);
        
        return {
          id: group.id.toString(),
          pid: group.pid.toString(),
          name: group.name,
          status: group.status,
          ruleCount: ruleCountResponse.data && 'code' in ruleCountResponse.data 
            ? ruleCountResponse.data.data?.length || 0
            : Array.isArray(ruleCountResponse.data) 
              ? ruleCountResponse.data.length 
              : 0
        };
      }));
    } else if (Array.isArray(childGroupsResponse.data)) {
      childGroups = await Promise.all(childGroupsResponse.data.map(async group => {
        // 获取该分组的评查点数量
        const ruleCountParams: PostgrestParams = {
          select: 'id',
          filter: {
            'evaluation_point_groups_id': `eq.${group.id}`
          }
        };
        
        const ruleCountResponse = await postgrestGet<{code: number; msg: string; data: Array<{id: number}>}>('evaluation_points', ruleCountParams);
        
        return {
          id: group.id.toString(),
          pid: group.pid.toString(),
          name: group.name,
          status: group.status,
          ruleCount: ruleCountResponse.data && 'code' in ruleCountResponse.data 
            ? ruleCountResponse.data.data?.length || 0
            : Array.isArray(ruleCountResponse.data) 
              ? ruleCountResponse.data.length 
              : 0
        };
      }));
    }
    
    return { data: childGroups };
  } catch (error) {
    console.error('获取子分组列表出错:', error);
    return { 
      error: error instanceof Error ? error.message : '获取子分组列表失败',
      status: 500
    };
  }
}

/**
 * 获取所有评查点分组（包括一级和二级）
 * @returns 完整的评查点分组列表
 */
export async function getAllRuleGroups(): Promise<{data: RuleGroup[]; error?: never} | {data?: never; error: string; status?: number}> {
  try {
    // 1. 获取所有分组
    const allGroupsParams: PostgrestParams = {
      select: `
        id,
        pid,
        name,
        status
      `
    };
    
    const allGroupsResponse = await postgrestGet<{code: number; msg: string; data: Array<{
      id: number;
      pid: number;
      name: string;
      status: boolean;
    }>}>('evaluation_point_groups', allGroupsParams);
    
    if (allGroupsResponse.error) {
      return { error: allGroupsResponse.error, status: allGroupsResponse.status };
    }
    
    // 2. 处理响应数据
    let allGroups: RuleGroup[] = [];
    if (allGroupsResponse.data && 'code' in allGroupsResponse.data && allGroupsResponse.data.data) {
      allGroups = allGroupsResponse.data.data.map(group => ({
        id: group.id.toString(),
        pid: group.pid.toString(),
        name: group.name,
        status: group.status,
        children: []
      }));
    } else if (Array.isArray(allGroupsResponse.data)) {
      allGroups = allGroupsResponse.data.map(group => ({
        id: group.id.toString(),
        pid: group.pid.toString(),
        name: group.name,
        status: group.status,
        children: []
      }));
    }
    
    // 3. 构建树形结构
    const parentGroups = allGroups.filter(group => group.pid === '0');
    
    // 4. 为每个父分组添加子分组
    for (const parent of parentGroups) {
      parent.children = allGroups.filter(group => group.pid === parent.id);
      
      // 5. 获取每个子分组的评查点数量
      for (const child of parent.children) {
        const ruleCountParams: PostgrestParams = {
          select: 'id',
          filter: {
            'evaluation_point_groups_id': `eq.${child.id}`
          }
        };
        
        const ruleCountResponse = await postgrestGet<{code: number; msg: string; data: Array<{id: number}>}>('evaluation_points', ruleCountParams);
        
        child.ruleCount = ruleCountResponse.data && 'code' in ruleCountResponse.data 
          ? ruleCountResponse.data.data?.length || 0
          : Array.isArray(ruleCountResponse.data) 
            ? ruleCountResponse.data.length 
            : 0;
      }
    }
    
    return { data: parentGroups };
  } catch (error) {
    console.error('获取所有评查点分组出错:', error);
    return { 
      error: error instanceof Error ? error.message : '获取所有评查点分组失败',
      status: 500
    };
  }
} 