import { postgrestGet, postgrestPost, postgrestPut, postgrestDelete, type PostgrestParams } from '../postgrest-client';
import dayjs from 'dayjs';

/**
 * 评查点分组接口
 */
export interface RuleGroup {
  id: string;
  pid: string;
  name: string;
  code?: string;   // 添加分组编码字段
  is_enabled: boolean;
  ruleCount?: number;  // 评查点数量
  children?: RuleGroup[];  // 子分组
  createdAt?: string;  // 添加创建时间字段
  description?: string; // 描述
}

// API请求模型
export interface ApiRuleGroup {
  id?: number;
  pid: number;
  name: string;
  code?: string;
  description?: string;
  is_enabled: boolean;
  created_at?: string;
  updated_at?: string;
}

// 创建或更新分组请求参数
export interface RuleGroupCreateUpdateDto {
  name: string;
  code: string;
  pid: string | null; // 父分组ID，如果是一级分组则为null或'0'
  description?: string;
  is_enabled: boolean;
}

// 用于替换代码中的 any 类型
interface ApiResponse<T> {
  code: number;
  msg: string;
  data: T;
}

/**
 * 格式化日期
 * @param dateString 日期字符串
 * @returns 格式化后的日期字符串
 */
function formatDate(dateString: string): string {
  if (!dateString) return '';
  try {
    return dayjs(dateString).format('YYYY-MM-DD HH:mm:ss');
  } catch (error) {
    console.error('日期格式化失败:', error);
    return dateString;
  }
}

/**
 * 从不同格式的 API 响应中提取数据
 * @param responseData API 响应数据
 * @returns 提取后的数据或 null
 */
function extractApiData<T>(responseData: unknown): T | null {
  if (!responseData) return null;
  
  // 格式1: { code: number, msg: string, data: T }
  if (typeof responseData === 'object' && responseData !== null && 
      'code' in responseData && 
      'data' in responseData && 
      (responseData as { data: unknown }).data) {
    return (responseData as { data: T }).data;
  }
  
  // 格式2: 直接是数据对象
  return responseData as T;
}

/**
 * 获取评查点分组列表
 * @returns 评查点分组列表
 */
export async function getRuleGroups(): Promise<{data: RuleGroup[]; error?: never} | {data?: never; error: string; status?: number}> {
  try {
    const params: PostgrestParams = {
      select: `
        id,
        pid,
        name,
        code,
        description,
        is_enabled,
        created_at
      `,
      filter: {
        'pid': 'eq.0'
      }
    };
    
    const response = await postgrestGet<{code: number; msg: string; data: Array<{
      id: number;
      pid: number;
      name: string;
      code?: string;
      description?: string;
      is_enabled: boolean;
      created_at?: string;
    }>}>('evaluation_point_groups', params);
    
    if (response.error) {
      return { error: response.error, status: response.status };
    }
    
    // 处理响应数据
    let groups: RuleGroup[] = [];
    if (response.data && 'code' in response.data && response.data.data) {
      groups = response.data.data.map(group => ({
        id: group.id.toString(),
        pid: group.pid.toString(),
        name: group.name,
        code: group.code,
        description: group.description,
        is_enabled: group.is_enabled,
        createdAt: group.created_at ? formatDate(group.created_at) : undefined
      }));
    } else if (Array.isArray(response.data)) {
      groups = response.data.map(group => ({
        id: group.id.toString(),
        pid: group.pid.toString(),
        name: group.name,
        code: group.code,
        description: group.description,
        is_enabled: group.is_enabled,
        createdAt: group.created_at ? formatDate(group.created_at) : undefined
      }));
    }
    
    return { data: groups };
  } 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,
        code,
        is_enabled,
        created_at
      `,
      filter: {
        'pid': `eq.${parentId}`
      }
    };
    
    const childGroupsResponse = await postgrestGet<{code: number; msg: string; data: Array<{
      id: number;
      pid: number;
      name: string;
      code?: string;
      is_enabled: boolean;
      created_at?: string;
    }>}>('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<ApiResponse<Array<{id: number}>>>('evaluation_points', ruleCountParams);
        
        return {
          id: group.id.toString(),
          pid: group.pid.toString(),
          name: group.name,
          code: group.code,
          is_enabled: group.is_enabled,
          createdAt: group.created_at ? formatDate(group.created_at) : undefined,
          ruleCount: ruleCountResponse.data && 'code' in ruleCountResponse.data 
            ? (ruleCountResponse.data.data && Array.isArray(ruleCountResponse.data.data) ? ruleCountResponse.data.data.length : 0)
            : (Array.isArray(ruleCountResponse.data) ? (ruleCountResponse.data as unknown[]).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<ApiResponse<Array<{id: number}>>>('evaluation_points', ruleCountParams);
        
        return {
          id: group.id.toString(),
          pid: group.pid.toString(),
          name: group.name,
          code: group.code,
          is_enabled: group.is_enabled,
          createdAt: group.created_at ? formatDate(group.created_at) : undefined,
          ruleCount: ruleCountResponse.data && 'code' in ruleCountResponse.data 
            ? (ruleCountResponse.data.data && Array.isArray(ruleCountResponse.data.data) ? ruleCountResponse.data.data.length : 0)
            : (Array.isArray(ruleCountResponse.data) ? (ruleCountResponse.data as unknown[]).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,
        is_enabled
      `
    };
    
    const allGroupsResponse = await postgrestGet<{code: number; msg: string; data: Array<{
      id: number;
      pid: number;
      name: string;
      is_enabled: 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,
        is_enabled: group.is_enabled,
        children: []
      }));
    } else if (Array.isArray(allGroupsResponse.data)) {
      allGroups = allGroupsResponse.data.map(group => ({
        id: group.id.toString(),
        pid: group.pid.toString(),
        name: group.name,
        is_enabled: group.is_enabled,
        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<ApiResponse<Array<{id: number}>>>('evaluation_points', ruleCountParams);
        
        child.ruleCount = ruleCountResponse.data && 'code' in ruleCountResponse.data 
          ? (ruleCountResponse.data.data && Array.isArray(ruleCountResponse.data.data) ? ruleCountResponse.data.data.length : 0)
          : (Array.isArray(ruleCountResponse.data) ? (ruleCountResponse.data as unknown[]).length : 0)
      }
    }
    
    return { data: parentGroups };
  } catch (error) {
    console.error('获取所有评查点分组出错:', error);
    return { 
      error: error instanceof Error ? error.message : '获取所有评查点分组失败',
      status: 500
    };
  }
}

/**
 * 获取单个评查点分组详情
 * @param id 分组ID
 * @returns 分组详情
 */
export async function getRuleGroup(id: string): Promise<{data: RuleGroup; error?: never} | {data?: never; error: string; status?: number}> {
  try {
    if (!id) {
      return { error: '分组ID不能为空', status: 400 };
    }
    
    const params: PostgrestParams = {
      select: `
        id,
        pid,
        name,
        code,
        description,
        is_enabled,
        created_at
      `,
      filter: {
        'id': `eq.${id}`
      }
    };
    
    const response = await postgrestGet<{code: number; msg: string; data: Array<{
      id: number;
      pid: number;
      name: string;
      code?: string;
      description?: string;
      is_enabled: boolean;
      created_at?: string;
    }>}>('evaluation_point_groups', params);
    
    if (response.error) {
      return { error: response.error, status: response.status };
    }
    
    let group: RuleGroup | null = null;
    
    if (response.data && 'code' in response.data && response.data.data && response.data.data.length > 0) {
      const apiGroup = response.data.data[0];
      group = {
        id: apiGroup.id.toString(),
        pid: apiGroup.pid.toString(),
        name: apiGroup.name,
        code: apiGroup.code,
        description: apiGroup.description,
        is_enabled: apiGroup.is_enabled,
        createdAt: apiGroup.created_at ? formatDate(apiGroup.created_at) : undefined
      };
    } else if (Array.isArray(response.data) && response.data.length > 0) {
      const apiGroup = response.data[0];
      group = {
        id: apiGroup.id.toString(),
        pid: apiGroup.pid.toString(),
        name: apiGroup.name,
        code: apiGroup.code,
        description: apiGroup.description,
        is_enabled: apiGroup.is_enabled,
        createdAt: apiGroup.created_at ? formatDate(apiGroup.created_at) : undefined
      };
    }
    
    if (!group) {
      return { error: '未找到指定分组', status: 404 };
    }
    
    // 如果是父分组，获取评查点数量
    if (group.pid === '0') {
      const ruleCountParams: PostgrestParams = {
        select: 'id',
        filter: {
          'evaluation_point_groups_id': `eq.${group.id}`
        }
      };
      
      const ruleCountResponse = await postgrestGet<ApiResponse<Array<{id: number}>>>('evaluation_points', ruleCountParams);
      
      group.ruleCount = ruleCountResponse.data && 'code' in ruleCountResponse.data 
        ? (ruleCountResponse.data.data && Array.isArray(ruleCountResponse.data.data) ? ruleCountResponse.data.data.length : 0)
        : (Array.isArray(ruleCountResponse.data) ? (ruleCountResponse.data as unknown[]).length : 0);
    }
    
    return { data: group };
  } catch (error) {
    console.error('获取评查点分组详情失败:', error);
    return { 
      error: error instanceof Error ? error.message : '获取评查点分组详情失败',
      status: 500
    };
  }
}

/**
 * 创建评查点分组
 * @param groupData 分组数据
 * @returns 创建的分组
 */
export async function createRuleGroup(groupData: RuleGroupCreateUpdateDto): Promise<{data: RuleGroup; error?: never} | {data?: never; error: string; status?: number}> {
  try {
    // 验证必填字段
    if (!groupData.name || !groupData.code) {
      return { error: '分组名称和编码不能为空', status: 400 };
    }
    
    // 确保 pid 是合法值
    let pidValue: number;
    try {
      pidValue = groupData.pid ? Number(groupData.pid) : 0;
      if (isNaN(pidValue)) {
        return { error: '父分组ID必须是有效的数字', status: 400 };
      }
    } catch (error) {
      console.error('父分组ID转换失败:', error);
      return { error: '父分组ID格式错误', status: 400 };
    }
    
    // 构建API请求数据 - 确保字段类型符合数据库要求
    const apiGroup: ApiRuleGroup = {
      pid: pidValue,
      name: groupData.name.trim(),
      code: groupData.code.trim(),
      description: groupData.description || '',
      is_enabled: groupData.is_enabled
    };
    
    console.log('创建评查点分组请求数据:', JSON.stringify(apiGroup, null, 2));
    
    // 直接发送到 PostgreSQL 表
    const response = await postgrestPost<ApiResponse<ApiRuleGroup> | ApiRuleGroup, ApiRuleGroup>(
      'evaluation_point_groups', // 表名
      apiGroup
    );
    
    if (response.error) {
      console.error('创建评查点分组API返回错误:', response.error, '状态码:', response.status);
      return { error: response.error, status: response.status };
    }
    
    console.log('创建评查点分组响应数据:', JSON.stringify(response.data, null, 2));
    
    // 处理响应数据 - 适配不同的API响应格式
    const apiResponse = extractApiData<ApiRuleGroup>(response.data);
    
    if (!apiResponse) {
      console.error('创建分组成功但返回数据格式异常:', response.data);
      return { error: '创建分组失败，返回数据格式错误', status: 500 };
    }
    
    // 构建返回对象
    const createdGroup: RuleGroup = {
      id: apiResponse.id?.toString() || '',
      pid: apiResponse.pid?.toString() || '0', // 兼容没有 pid 的情况
      name: apiResponse.name || '',
      code: apiResponse.code?.toString() || '', // 处理可能的数字类型
      description: apiResponse.description,
      is_enabled: apiResponse.is_enabled !== undefined ? apiResponse.is_enabled : true,
      createdAt: apiResponse.created_at ? formatDate(apiResponse.created_at) : undefined
    };
    
    return { data: createdGroup };
  } catch (error) {
    console.error('创建评查点分组失败:', error);
    return { 
      error: error instanceof Error ? error.message : '创建评查点分组失败',
      status: 500
    };
  }
}

/**
 * 更新评查点分组
 * @param id 分组ID
 * @param data 更新的分组数据
 * @returns 更新后的分组
 */
export async function updateRuleGroup(id: string, data: RuleGroupCreateUpdateDto): Promise<{data: RuleGroup; error?: never} | {data?: never; error: string; status?: number}> {
  try {
    // 使用新的filters参数
    const response = await postgrestPut<ApiResponse<RuleGroup> | RuleGroup, RuleGroupCreateUpdateDto>(
      'evaluation_point_groups',
      data,
      { id }
    );
    
    if (response.error) {
      return { error: response.error, status: response.status };
    }
    
    // 使用辅助函数提取数据
    const extractedData = extractApiData<RuleGroup>(response.data);
    
    if (!extractedData) {
      return { error: '更新成功但未返回数据' };
    }
    
    return { data: extractedData };
  } catch (error) {
    console.error('更新评查点分组失败:', error);
    return { 
      error: error instanceof Error ? error.message : '更新评查点分组失败' 
    };
  }
}

/**
 * 删除评查点分组
 * @param id 分组ID
 * @returns 删除结果
 */
export async function deleteRuleGroup(id: string): Promise<{success: boolean; error?: string}> {
  try {
    // 1. 首先获取分组信息，判断是一级还是二级分组
    const groupResponse = await getRuleGroup(id);
    if (groupResponse.error) {
      return { success: false, error: groupResponse.error };
    }

    const group = groupResponse.data;
    if (!group) {
      return { success: false, error: '未找到指定分组' };
    }

    // 2. 如果是一级分组，需要先删除所有子分组
    if (group.pid === '0') {
      // 获取所有子分组
      const childGroupsResponse = await getChildGroups(id);
      if (childGroupsResponse.error) {
        return { success: false, error: childGroupsResponse.error };
      }

      const childGroups = childGroupsResponse.data || [];
      
      // 遍历删除每个子分组
      for (const childGroup of childGroups) {
        const deleteChildResult = await deleteChildGroup(childGroup.id);
        if (!deleteChildResult.success) {
          return deleteChildResult;
        }
      }
    }

    // 3. 删除分组下的所有评查点
    const deletePointsResult = await deleteEvaluationPointsByGroupId(id);
    if (!deletePointsResult.success) {
      return deletePointsResult;
    }

    // 4. 最后删除分组本身
    const response = await postgrestDelete<ApiResponse<{id: number}>>('evaluation_point_groups', {
      filter: {
        'id': `eq.${id}`
      }
    });

    if (response.error) {
      return { success: false, error: response.error };
    }

    return { success: true };
  } catch (error) {
    console.error('删除评查点分组失败:', error);
    return { 
      success: false, 
      error: error instanceof Error ? error.message : '删除评查点分组失败'
    };
  }
}

/**
 * 删除子分组及其相关数据
 * @param id 子分组ID
 * @returns 删除结果
 */
async function deleteChildGroup(id: string): Promise<{success: boolean; error?: string}> {
  try {
    // 1. 删除子分组下的所有评查点
    const deletePointsResult = await deleteEvaluationPointsByGroupId(id);
    if (!deletePointsResult.success) {
      return deletePointsResult;
    }

    // 2. 删除子分组本身
    const response = await postgrestDelete<ApiResponse<{id: number}>>('evaluation_point_groups', {
      filter: {
        'id': `eq.${id}`
      }
    });

    if (response.error) {
      return { success: false, error: response.error };
    }

    return { success: true };
  } catch (error) {
    console.error('删除子分组失败:', error);
    return { 
      success: false, 
      error: error instanceof Error ? error.message : '删除子分组失败'
    };
  }
}

/**
 * 删除指定分组下的所有评查点
 * @param groupId 分组ID
 * @returns 删除结果
 */
async function deleteEvaluationPointsByGroupId(groupId: string): Promise<{success: boolean; error?: string}> {
  try {
    const response = await postgrestDelete<ApiResponse<{id: number}>>('evaluation_points', {
      filter: {
        'evaluation_point_groups_id': `eq.${groupId}`
      }
    });

    if (response.error) {
      return { success: false, error: response.error };
    }

    return { success: true };
  } catch (error) {
    console.error('删除评查点失败:', error);
    return { 
      success: false, 
      error: error instanceof Error ? error.message : '删除评查点失败'
    };
  }
} 