/**
 * 作者: 阿瑞
 * 功能: 店铺成交分析数据API
 * 版本: 1.0.0
 * 文件有问题！！！！！api处理方式不对！！！！待修复
 */
import { NextResponse, NextRequest } from "next/server";
import { teamDbManager } from '@/lib/db';
import { Shop } from "@/lib/db/types";
import { RowDataPacket } from 'mysql2';

/**
 * 类型定义
 */
interface ShopRow extends Shop, RowDataPacket {}
interface FollowerResult extends RowDataPacket { total_followers: number }
interface ExpenseResult extends RowDataPacket { total_expenses: number }
interface SalesResult extends RowDataPacket { 
  order_count: number; 
  total_sales: number;
}
interface CostResult extends RowDataPacket { total_cost: number }

/**
 * 处理获取店铺成交分析数据的请求
 */
export async function GET(request: NextRequest) {
  try {
    // 从URL路径中提取团队代码
    const pathname = request.nextUrl.pathname;
    const teamCode = pathname.split('/')[3]; // /api/team/[teamCode]/shop-sales-analysis
    
    if (!teamCode) {
      return NextResponse.json(
        { error: "团队代码不能为空" },
        { status: 400 }
      );
    }

    // 获取查询参数
    const searchParams = request.nextUrl.searchParams;
    const startDate = searchParams.get("startDate");
    const endDate = searchParams.get("endDate");

    if (!startDate || !endDate) {
      return NextResponse.json(
        { error: "开始日期和结束日期是必填参数" },
        { status: 400 }
      );
    }

    // 获取团队数据库连接
    const teamDBInfo = await teamDbManager.getTeamDBInfoByCode(teamCode);
    if (!teamDBInfo) {
      return NextResponse.json(
        { error: "无法获取团队信息，请确保团队代码有效" },
        { status: 400 }
      );
    }

    // 使用团队数据库管理器获取连接池
    const teamPool = teamDbManager.getTeamDbPool(teamDBInfo);
    
    // 从连接池获取连接
    const connection = await teamPool.getConnection();
    console.log(`🟢 MySQL 团队数据库连接已获取: ${teamDBInfo.dbHost}/${teamDBInfo.dbName}`);

    try {
      // 获取所有店铺数据
      const [shops] = await connection.query<ShopRow[]>(`
        SELECT id, nickname, wechat, account_no FROM shops WHERE status = 1
      `);

      // 获取分析数据
      const results = await Promise.all(
        shops.map(async (shop: ShopRow) => {
          // 获取进粉数量 (来自shop_follower_growth表，计算日增长人数总和)
          const [followersResult] = await connection.query<FollowerResult[]>(`
            SELECT COALESCE(SUM(daily_increase), 0) as total_followers 
            FROM shop_follower_growth 
            WHERE shop_id = ? AND date BETWEEN ? AND ?
          `, [shop.id, startDate, endDate]);
          
          // 获取引流消费 (来自shop_traffic_expenses表)
          const [expensesResult] = await connection.query<ExpenseResult[]>(`
            SELECT COALESCE(SUM(expense_amount), 0) as total_expenses 
            FROM shop_traffic_expenses 
            WHERE shop_id = ? AND DATE(record_time) BETWEEN ? AND ?
          `, [shop.id, startDate, endDate]);
          
          // 获取出单数和销售额 (来自sales_records表)
          const [salesResult] = await connection.query<SalesResult[]>(`
            SELECT 
              COUNT(*) as order_count,
              COALESCE(SUM(receivable), 0) as total_sales
            FROM sales_records 
            WHERE source_id = ? AND deal_date BETWEEN ? AND ?
          `, [shop.id, startDate, endDate]);

          // 获取成本 (从sales_records关联到sales_record_products再到products表)
          const [costResult] = await connection.query<CostResult[]>(`
            SELECT COALESCE(SUM(p.cost->>'$.cost_price' * srp.quantity), 0) as total_cost
            FROM sales_records sr
            JOIN sales_record_products srp ON sr.id = srp.sales_record_id
            JOIN products p ON srp.product_id = p.id
            WHERE sr.source_id = ? AND sr.deal_date BETWEEN ? AND ?
          `, [shop.id, startDate, endDate]);

          return {
            shopId: shop.id,
            shopName: shop.nickname || shop.wechat || shop.account_no || `店铺${shop.id}`,
            followers: followersResult[0]?.total_followers || 0,
            expenses: expensesResult[0]?.total_expenses || 0,
            orderCount: salesResult[0]?.order_count || 0,
            sales: salesResult[0]?.total_sales || 0,
            cost: costResult[0]?.total_cost || 0
          };
        })
      );

      // 释放连接
      connection.release();
      console.log(`🟢 MySQL 团队数据库连接已释放: ${teamDBInfo.dbHost}/${teamDBInfo.dbName}`);

      return NextResponse.json({ success: true, data: results });
    } catch (error) {
      // 确保释放连接
      connection.release();
      console.log(`🟢 MySQL 团队数据库连接已释放（异常）: ${teamDBInfo.dbHost}/${teamDBInfo.dbName}`);
      throw error;
    }
  } catch (error) {
    console.error("获取店铺成交分析数据失败:", error);
    return NextResponse.json(
      { error: "获取店铺成交分析数据失败" },
      { status: 500 }
    );
  }
}
