package com.fs.company.controller.fastGpt;

import com.fs.common.constant.HttpStatus;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.page.PageDomain;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.core.page.TableSupport;
import com.fs.common.utils.ServletUtils;
import com.fs.fastGpt.domain.FastGptPushTokenTotal;
import com.fs.framework.security.LoginUser;
import com.fs.framework.service.TokenService;
import com.fs.qw.service.IQwPushCountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * FastGPT推送Token统计Controller
 *
 * @author fs
 * @date 2025-12-24
 */
@RestController
@RequestMapping("/fastGpt/pushTokenTotal")
public class FastGptPushTokenTotalController extends BaseController {

    @Autowired
    private IQwPushCountService qwPushCountService;

    @Autowired
    private TokenService tokenService;

    /**
     * 查询FastGPT推送Token统计列表
     * 每个公司只能查看自己公司的数据
     */
    @GetMapping("/list")
    public TableDataInfo tokenList(FastGptPushTokenTotal pushTokenInfo) {
        // 获取当前登录用户的公司ID
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long companyId = loginUser.getCompany().getCompanyId();

        // 强制设置查询条件为当前公司ID,确保只能查看自己公司的数据
        pushTokenInfo.setCompanyId(companyId);

        // 查询数据
        List<FastGptPushTokenTotal> list = qwPushCountService.selectFastGptPushTokenTotalList(pushTokenInfo);

        // 金额一律由本行 token 计算，不用库里已四舍五入的 amount 累加
        for (FastGptPushTokenTotal item : list) {
            item.setAmount(FastGptPushTokenTotal.calcAmountByCount(item.getCount()));
        }

        // 合计：先汇总 token，再按总 token 算金额（避免各行金额再求和导致精度丢失）
        FastGptPushTokenTotal sumTotal = new FastGptPushTokenTotal();
        sumTotal.setCompanyName("合计");
        Long sum = list.stream()
                .map(FastGptPushTokenTotal::getCount)
                .filter(Objects::nonNull)
                .mapToLong(Long::longValue)
                .sum();
        sumTotal.setCount(sum);
        sumTotal.setAmount(FastGptPushTokenTotal.calcAmountByCount(sum));

        // 获取分页参数
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();

        int total = list.size();

        // 在内存中进行分页处理
        if (pageNum != null && pageSize != null) {
            int fromIndex = (pageNum - 1) * pageSize;
            int toIndex = Math.min(fromIndex + pageSize, total);

            // 确保索引不越界
            if (fromIndex < total) {
                list = list.subList(fromIndex, toIndex);
            } else {
                list = new ArrayList<>(); // 返回空列表
            }
        }

        // 将合计行添加到列表末尾
        list.add(sumTotal);

        // 构造返回结果
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(list);
        rspData.setTotal(total);
        return rspData;
    }
}
