// controllers/paymentStats.ts
import { Request, Response } from "express";
import { getRepository } from "typeorm";
import dayjs from "dayjs";
import CheckoutPaymentRecords from "@/entity/CheckoutPayment";
import PaymentRecord from "@/entity/Payment";
import DeceasedRetail from "@/entity/DeceasedRetail";
import parseRangDate, { handleError } from "@/util/globalMethods";

// 类型定义
type PaymentStats = {
  cashAmount: number;
  unionPayAmount: number;
  cardAmount: number;
  publicTransferAmount: number;
  workshopPayment: number;
};

type StatsResponse = {
  retail: PaymentStats; // 零售单统计（来自PaymentRecord）
  service: PaymentStats; // 服务单统计（来自CheckoutPaymentRecords）
  total: PaymentStats; // 合并统计
};

export const getPaymentStats = async (req: Request, res: Response) => {
  try {
    // 参数处理
    const { startDate, endDate } = parseRangDate(req);

    // 并行获取统计结果
    const [retailStats, serviceStats] = await Promise.all([
      getRetailStats(startDate, endDate),
      getServiceStats(startDate, endDate),
    ]);

    // 构建响应
    const response: StatsResponse = {
      retail: retailStats,
      service: serviceStats,
      total: {
        cashAmount: retailStats.cashAmount + serviceStats.cashAmount,
        unionPayAmount:
          retailStats.unionPayAmount + serviceStats.unionPayAmount,
        cardAmount: retailStats.cardAmount + serviceStats.cardAmount,
        publicTransferAmount:
          retailStats.publicTransferAmount + serviceStats.publicTransferAmount,
        workshopPayment:
          retailStats.workshopPayment + serviceStats.workshopPayment,
      },
    };

    res.json({ code: 200, data: response });
  } catch (error) {
    handleError(res, error);
  }
};

// 修改后的获取零售单统计
const getRetailStats = async (
  start: string,
  end: string
): Promise<PaymentStats> => {
  const result = await getRepository(PaymentRecord)
    .createQueryBuilder("payment")
    .select([
      "SUM(payment.cash_amount) AS cashAmount",
      "SUM(payment.union_pay_amount) AS unionPayAmount",
      "SUM(payment.card_amount) AS cardAmount",
      "SUM(payment.public_transfer_amount) AS publicTransferAmount",
      "SUM(payment.workshop_payment) AS workshopPayment",
    ])
    .where("payment.checkout_date BETWEEN :start AND :end", { start, end })
    .andWhere(
      `(payment.deceased_retail_id IN (
        SELECT id 
        FROM deceased_retail 
        WHERE retail_state = 1
      ) OR payment.no_deceased_retail_id IN (
        SELECT id 
        FROM deceased_retail 
        WHERE retail_state = 1
      ))`
    )
    .getRawOne();

  return formatStats(result);
};

// 修改后的获取服务单统计
const getServiceStats = async (
  start: string,
  end: string
): Promise<PaymentStats> => {
  const result = await getRepository(CheckoutPaymentRecords)
    .createQueryBuilder("cpr")
    .innerJoin(
      DeceasedRetail,
      "dr",
      "dr.id = cpr.checkout_retail_id AND dr.retail_state = 1"
    )
    .select([
      "SUM(cpr.cash_amount) AS cashAmount",
      "SUM(cpr.union_pay_amount) AS unionPayAmount",
      "SUM(cpr.card_amount) AS cardAmount",
      "SUM(cpr.public_transfer_amount) AS publicTransferAmount",
      "SUM(cpr.workshop_payment) AS workshopPayment",
    ])
    .where("cpr.checkout_date BETWEEN :start AND :end", { start, end })
    .getRawOne();

  return formatStats(result);
};

/** 格式化统计结果 */
const formatStats = (raw: any): PaymentStats => ({
  cashAmount: Number(raw?.cashAmount || 0),
  unionPayAmount: Number(raw?.unionPayAmount || 0),
  cardAmount: Number(raw?.cardAmount || 0),
  publicTransferAmount: Number(raw?.publicTransferAmount || 0),
  workshopPayment: Number(raw?.workshopPayment || 0),
});
