package modules.user;

import com.jfinal.plugin.activerecord.Db;
import common.model.BalanceLog;
import common.utils.http.MyRet;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BalanceLogService {    
    public MyRet findForUser(int pageNumber, int pageSize, long userId) {
        String columns = "id, amount, description, create_time";
        String select = "SELECT " + columns;
        String fromWhere = "FROM t_balance_log WHERE user_id = ?"; // 基础 from 子句
        String orderBy = "ORDER BY create_time DESC";

        List<Object> paramsForList = new ArrayList<>(); // 用于 SELECT 列表查询的参数

        // 计算 LIMIT 的 offset (偏移量)
        int offset = (pageNumber - 1) * pageSize;

        // 构建查询当前页订单列表的最终 SQL (手动添加 LIMIT)
        String listSql = select + " " + fromWhere + " " + orderBy + " LIMIT ?, ?";
        paramsForList.add(userId);
        paramsForList.add(offset);
        paramsForList.add(pageSize);
        
        List<BalanceLog> logs = BalanceLog.dao.find(listSql, paramsForList.toArray());
        // 如果列表为空，直接返回
        if (logs.isEmpty()) {
            Map<String, Object> response = new HashMap<>(); // 准备返回结构
            response.put("list", new ArrayList<>());
            response.put("total_row", 0);
            response.put("total_page", 0);
            response.put("page_size", pageSize);
            response.put("page_number", pageNumber);
            response.put("total_order_count", 0); // 与你的 total_user_count 对应
            return MyRet.ok("查询成功").setData(response);
        }
        
        long totalRowLong = Db.queryLong("SELECT COUNT(id) FROM t_balance_log WHERE user_id=?", userId);
        // 手动计算 total_page
        int totalPage = (int) Math.ceil((double) totalRowLong / pageSize);
        if (totalPage == 0 && totalRowLong > 0) { // 解决总行数大于0但总页数为0（pageSize大于totalRow）的问题
            totalPage = 1;
        }

        // 封装最终响应
        Map<String, Object> response = new HashMap<>();
        response.put("list", logs);
        response.put("total_row", totalRowLong); // 符合条件的订单总数
        response.put("total_page", totalPage); // 手动计算的总页数
        response.put("page_size", pageSize);
        response.put("page_number", pageNumber);
        response.put("total_order_count", totalRowLong); // 对应 total_user_count，这里是符合订单状态筛选的总数

        return MyRet.ok("查询成功").setData(response);
    }
}
