package com.cyksj.web.controller.codex;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.constant.Constant;
import com.cyksj.common.util.Jsons;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.mapper.CodexUserMapper;
import com.cyksj.mapper.GroupsMapper;
import com.cyksj.mapper.GroupsRelationMapper;
import com.cyksj.model.entity.CodexUser;
import com.cyksj.model.entity.GroupsRelation;
import com.cyksj.model.entity.GroupsTrips;
import com.cyksj.model.entity.OrderDon;
import com.cyksj.model.request.CodexUpgradePayReq;
import com.cyksj.model.request.UpdateDailyLimitRequest;
import com.cyksj.model.response.CodexDeductResp;
import com.cyksj.model.response.claudecode.ClaudeCodeResp;
import com.cyksj.model.views.*;
import com.cyksj.service.codex.CodexService;
import com.cyksj.service.user.UserBindRelationService;
import com.cyksj.web.util.StpUserUtil;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.param.Operator;
import com.ejlchina.searcher.util.MapUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

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

/**
 * server/codex
 * server/codex
 * 项目名: yhlxj11111111
 * 文件名: CodexController
 * 创建者: Claude
 * 创建时间:2025/9/15
 */
@Slf4j
@RestController
@RequestMapping("/applet/codex")
@RequiredArgsConstructor
public class CodexController {
    
    private final CodexService codexService;

    private final UserBindRelationService userBindRelationService;

    private final CodexUserMapper codexUserMapper;

    private final GroupsRelationMapper relationMapper;

    private final GroupsMapper groupsMapper;

    private final BeanSearcher beanSearcher;


    /**
     * codex 用户是否存在订阅
     */
    @GetMapping("/get/user/subs")
    public Result<Boolean> getUserSubs() {
        long userId = StpUserUtil.getLoginIdAsLong();
        Boolean flag = codexService.getUserSubs(userId);
        return GatewayResponse.SUCCESS.newBuilder().toResult(flag);
    }

    /**
     * codex 用户订阅车票信息
     */
    @GetMapping("/get/user/subs/info")
    public Result<CodexUserInfoView> getUserSubsInfo() {
        long userId = StpUserUtil.getLoginIdAsLong();
        CodexUserInfoView codexUserInfoView = codexService.getUserSubsInfo(userId);
        return GatewayResponse.SUCCESS.newBuilder().toResult(codexUserInfoView);
    }

    /**
     * 获取用户OpenAI使用统计
     * period 时间周期(today/7d/30d)
     */
    @GetMapping("/users/usage")
    public ClaudeCodeResp getUserOpenAIUsage(@RequestParam(defaultValue = "today") String period) {
        long userId = StpUserUtil.getLoginIdAsLong();
        ClaudeCodeResp claudeCodeResp = codexService.getUserOpenAIUsage(userId, period);
        return claudeCodeResp;
    }
    
    /**
     * 更新用户OpenAI每日美金限额
     */
    @PostMapping("/users/daily-limit")
    public Result<ClaudeCodeResp> updateUserOpenAIDailyLimit(@RequestBody UpdateDailyLimitRequest request) {
        // 验证请求用户是否为当前登录用户或有权限访问
        long userId = StpUserUtil.getLoginIdAsLong();
        ClaudeCodeResp response = codexService.updateUserOpenAIDailyLimit(userId, request);
        return GatewayResponse.SUCCESS.newBuilder().toResult(response);
    }
    
    /**
     * codex 仪表盘
     * 用户OpenAI控制台数据 (Java系统专用接口)
     */
    @GetMapping("/openai/users/dashboard")
    public ClaudeCodeResp getJavaUserDashboard() {
        long userId = StpUserUtil.getLoginIdAsLong();
        ClaudeCodeResp dashboard = codexService.getJavaUserDashboard(userId);
        return dashboard;
    }

    /**
     * 用户OpenAI图表+明细联动 (Java系统专用接口)
     */
    @GetMapping("/openai/users/analytics")
    public ClaudeCodeResp getJavaUserAnalytics(String start, String end, @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer limit, @RequestParam(defaultValue = "desc") String order) {
        long userId = StpUserUtil.getLoginIdAsLong();
        ClaudeCodeResp analytics = codexService.getJavaUserAnalytics(userId, start, end, page, limit, order);
        return analytics;
    }

    /**
     * 抵扣车票金额
     */
    @GetMapping("/get/deduct/money")
    public Result<CodexDeductResp> getDeductMoney() {
        long userId = StpUserUtil.getLoginIdAsLong();
        CodexDeductResp codexDeductResp = codexService.getDeductMoney(userId, null);
        return GatewayResponse.SUCCESS.newBuilder().toResult(codexDeductResp);
    }

    /**
     * codex 抵扣升级 预下单
     */
    @PostMapping("/deduct/submit/order")
    public Result<OrderDon> deductSubmitOrder(@RequestBody CodexUpgradePayReq payReq) throws Exception {
        long userId = StpUserUtil.getLoginIdAsLong();
        payReq.setUserId(userId);
        OrderDon orderDon = codexService.deductSubmitOrder(payReq);
        return GatewayResponse.SUCCESS.newBuilder().toResult(orderDon);
    }

    /**
     * codex续费升级 可选套餐
     */
    @GetMapping("/get/packages")
    public Result<ClaudeCodePackageView> getClaudeCodePackages(String dsCode) {
        Long userId = StpUserUtil.getUserIdAfterLogin();
        ClaudeCodePackageView claudeCodePackageView = new ClaudeCodePackageView();
        if (userId != null) {
            List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
            CodexUser user = codexUserMapper.selectOne(Wrappers.lambdaQuery(CodexUser.class)
                    .in(CodexUser::getUserId, userIdList)
                    .last("limit 1"));
            if (user != null) {
                Integer openaiDailyLimit = user.getOpenaiDailyLimit();
                GroupsRelation relation = relationMapper.selectById(user.getRelationId());
                GroupsTrips groupsTrips = groupsMapper.selectById(relation.getGroupsId());
                Long skuId = groupsTrips.getSkuId();
                List<RenewUpgradePackageFrontView> renewUpgradePackageFrontViews = beanSearcher.searchAll(RenewUpgradePackageFrontView.class, MapUtils.builder().field(RenewUpgradePackageFrontView::getSkuId, skuId).build());
                renewUpgradePackageFrontViews.forEach(renew -> {
                    try {
                        List<Long> upgradeSkuIds = Jsons.parseList(renew.getUpgradeSkuIds(), Long.class);
                        if (user.getRenewSkuId() != null) {
                            upgradeSkuIds.remove(user.getRenewSkuId());
                        }
                        List<RenewUpgradePackageFrontView.RenewSkuView> renewSkuViews = new ArrayList<>();
                        if (CollUtil.isNotEmpty(upgradeSkuIds)) {
                            renewSkuViews = beanSearcher.searchAll(RenewUpgradePackageFrontView.RenewSkuView.class, MapUtils.builder()
                                    //高套餐
                                    .field(RenewUpgradePackageFrontView.RenewSkuView::getOpenaiDailyLimit, openaiDailyLimit).op(Operator.GreaterThan)
                                    .field(RenewUpgradePackageFrontView.RenewSkuView::getSkuId, upgradeSkuIds).op(Operator.InList)
                                    .build());
                        }
                        renew.setRenewSkus(renewSkuViews);
                    } catch (Exception e) {
                    }
                });
                claudeCodePackageView.setUpgrades(renewUpgradePackageFrontViews);
            }
        }
        List<GoodsDonSkuView> goodsDonSkuViews = beanSearcher.searchAll(GoodsDonSkuView.class, MapUtils.builder().field(GoodsDonSkuView::getGoodsId, Constant.CODEX_GOODS_ID).field(GoodsDonSkuView::getGoodsDonStatus, Boolean.TRUE).field(GoodsDonSkuView::getGoodsDonSkuStatus, Boolean.TRUE).field(GoodsDonSkuView::getUserOwns).op(Operator.IsNull).build());
        claudeCodePackageView.setSkus(goodsDonSkuViews);
        return GatewayResponse.SUCCESS.newBuilder().toResult(claudeCodePackageView);
    }
}