package com.xy.xyaicpzs.controller;

import com.xy.xyaicpzs.common.ErrorCode;
import com.xy.xyaicpzs.common.ResultUtils;
import com.xy.xyaicpzs.common.response.ApiResponse;
import com.xy.xyaicpzs.domain.vo.DLTFirstStepResultVO;
import com.xy.xyaicpzs.domain.vo.DLTSecondStepResultVO;
import com.xy.xyaicpzs.domain.vo.DLTThirdStepResultVO;
import com.xy.xyaicpzs.domain.vo.DLTFourthStepResultVO;
import com.xy.xyaicpzs.jt.jtdlt.FirstFrontBallAnalysis;
import com.xy.xyaicpzs.jt.jtdlt.FollowFrontBallAnalysis;
import com.xy.xyaicpzs.jt.jtdlt.BackBallAnalysis;
import com.xy.xyaicpzs.jt.jtdlt.FollowBackendBallAnalysis;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/jtdlt/analysis")
@Tag(name = "精推大乐透分析", description = "精推大乐透分析算法API")
public class JtDltController {
    
    @Autowired
    private FirstFrontBallAnalysis firstFrontBallAnalysis;
    
    @Autowired
    private FollowFrontBallAnalysis followFrontBallAnalysis;
    
    @Autowired
    private BackBallAnalysis backBallAnalysis;
    
    @Autowired
    private FollowBackendBallAnalysis followBackendBallAnalysis;
    
    /**
     * 精推大乐透第一步分析
     */
    @PostMapping("/first-step")
    @Operation(summary = "精推大乐透第一步分析", description = "根据前区5个球号和后区2个球号进行第一步分析")
    public ApiResponse<DLTFirstStepResultVO> firstStepAnalysis(
            @Parameter(description = "策略级别（H-高位/M-中位/L-低位）", required = true)
            @RequestParam String level,
            @Parameter(description = "前区球号列表（逗号分隔，如：1,5,12,18,22）", required = true)
            @RequestParam String frontBalls,
            @Parameter(description = "后区球号列表（逗号分隔，如：3,7）", required = true)
            @RequestParam String backBalls) {
        
        try {
            // 参数验证
            if (!"H".equalsIgnoreCase(level) && !"M".equalsIgnoreCase(level) && !"L".equalsIgnoreCase(level)) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "策略级别必须是H/M/L之一");
            }
            
            // 解析前区球号
            String[] frontBallArray = frontBalls.split(",");
            if (frontBallArray.length != 5) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "前区球号必须为5个");
            }
            
            List<Integer> frontBallList = java.util.Arrays.stream(frontBallArray)
                    .map(s -> {
                        try {
                            int ball = Integer.parseInt(s.trim());
                            if (ball < 1 || ball > 35) {
                                throw new IllegalArgumentException("前区球号范围应为1-35");
                            }
                            return ball;
                        } catch (NumberFormatException e) {
                            throw new IllegalArgumentException("前区球号格式错误");
                        }
                    })
                    .collect(java.util.stream.Collectors.toList());
            
            // 解析后区球号
            String[] backBallArray = backBalls.split(",");
            if (backBallArray.length != 2) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "后区球号必须为2个");
            }
            
            List<Integer> backBallList = java.util.Arrays.stream(backBallArray)
                    .map(s -> {
                        try {
                            int ball = Integer.parseInt(s.trim());
                            if (ball < 1 || ball > 12) {
                                throw new IllegalArgumentException("后区球号范围应为1-12");
                            }
                            return ball;
                        } catch (NumberFormatException e) {
                            throw new IllegalArgumentException("后区球号格式错误");
                        }
                    })
                    .collect(java.util.stream.Collectors.toList());
            
            log.info("精推大乐透第一步分析请求：策略={}, 前区={}, 后区={}", level, frontBallList, backBallList);
            
            // 调用分析算法
            DLTFirstStepResultVO result = firstFrontBallAnalysis.analyze(level, frontBallList, backBallList);
            
            log.info("精推大乐透第一步分析完成，返回{}个结果", result.getResults().size());
            
            return ResultUtils.success(result);
            
        } catch (Exception e) {
            log.error("精推大乐透第一步分析失败", e);
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "分析失败：" + e.getMessage());
        }
    }
    
    /**
     * 精推大乐透第二步分析
     */
    @PostMapping("/second-step")
    @Operation(summary = "精推大乐透第二步分析", description = "根据上期前区5个球号、上期后区2个球号和本期首球进行第二步分析")
    public ApiResponse<DLTSecondStepResultVO> secondStepAnalysis(
            @Parameter(description = "策略级别（H-高位/M-中位/L-低位）", required = true)
            @RequestParam String level,
            @Parameter(description = "上期前区球号列表（逗号分隔，如：1,5,12,18,22）", required = true)
            @RequestParam String previousFrontBalls,
            @Parameter(description = "上期后区球号列表（逗号分隔，如：3,7）", required = true)
            @RequestParam String previousBackBalls,
            @Parameter(description = "本期首球号码", required = true)
            @RequestParam Integer currentFirstBall) {
        
        try {
            // 参数验证
            if (!"H".equalsIgnoreCase(level) && !"M".equalsIgnoreCase(level) && !"L".equalsIgnoreCase(level)) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "策略级别必须是H/M/L之一");
            }
            
            if (currentFirstBall == null || currentFirstBall < 1 || currentFirstBall > 35) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "本期首球号码范围应为1-35");
            }
            
            // 解析上期前区球号
            String[] previousFrontBallArray = previousFrontBalls.split(",");
            if (previousFrontBallArray.length != 5) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "上期前区球号必须为5个");
            }
            
            List<Integer> previousFrontBallList = java.util.Arrays.stream(previousFrontBallArray)
                    .map(s -> {
                        try {
                            int ball = Integer.parseInt(s.trim());
                            if (ball < 1 || ball > 35) {
                                throw new IllegalArgumentException("上期前区球号范围应为1-35");
                            }
                            return ball;
                        } catch (NumberFormatException e) {
                            throw new IllegalArgumentException("上期前区球号格式错误");
                        }
                    })
                    .collect(java.util.stream.Collectors.toList());
            
            // 解析上期后区球号
            String[] previousBackBallArray = previousBackBalls.split(",");
            if (previousBackBallArray.length != 2) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "上期后区球号必须为2个");
            }
            
            List<Integer> previousBackBallList = java.util.Arrays.stream(previousBackBallArray)
                    .map(s -> {
                        try {
                            int ball = Integer.parseInt(s.trim());
                            if (ball < 1 || ball > 12) {
                                throw new IllegalArgumentException("上期后区球号范围应为1-12");
                            }
                            return ball;
                        } catch (NumberFormatException e) {
                            throw new IllegalArgumentException("上期后区球号格式错误");
                        }
                    })
                    .collect(java.util.stream.Collectors.toList());
            
            log.info("精推大乐透第二步分析请求：策略={}, 上期前区={}, 上期后区={}, 本期首球={}", 
                    level, previousFrontBallList, previousBackBallList, currentFirstBall);
            
            // 调用分析算法
            DLTSecondStepResultVO result = followFrontBallAnalysis.analyze(level, previousFrontBallList, 
                    previousBackBallList, currentFirstBall);
            
            log.info("精推大乐透第二步分析完成，返回{}个结果", result.getResults().size());
            
            return ResultUtils.success(result);
            
        } catch (Exception e) {
            log.error("精推大乐透第二步分析失败", e);
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "分析失败：" + e.getMessage());
        }
    }
    
    /**
     * 精推大乐透第三步分析
     */
    @PostMapping("/third-step")
    @Operation(summary = "精推大乐透第三步分析", description = "根据上期前区5个球号、上期后区2个球号和本期前区5个球号进行第三步分析")
    public ApiResponse<DLTThirdStepResultVO> thirdStepAnalysis(
            @Parameter(description = "策略级别（H-高位/M-中位/L-低位）", required = true)
            @RequestParam String level,
            @Parameter(description = "上期前区球号列表（逗号分隔，如：1,5,12,18,22）", required = true)
            @RequestParam String previousFrontBalls,
            @Parameter(description = "上期后区球号列表（逗号分隔，如：3,7）", required = true)
            @RequestParam String previousBackBalls,
            @Parameter(description = "本期前区球号列表（逗号分隔，如：2,9,16,23,29）", required = true)
            @RequestParam String currentFrontBalls) {
        
        try {
            // 参数验证
            if (!"H".equalsIgnoreCase(level) && !"M".equalsIgnoreCase(level) && !"L".equalsIgnoreCase(level)) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "策略级别必须是H/M/L之一");
            }
            
            // 解析上期前区球号
            String[] previousFrontBallArray = previousFrontBalls.split(",");
            if (previousFrontBallArray.length != 5) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "上期前区球号必须为5个");
            }
            
            List<Integer> previousFrontBallList = java.util.Arrays.stream(previousFrontBallArray)
                    .map(s -> {
                        try {
                            int ball = Integer.parseInt(s.trim());
                            if (ball < 1 || ball > 35) {
                                throw new IllegalArgumentException("上期前区球号范围应为1-35");
                            }
                            return ball;
                        } catch (NumberFormatException e) {
                            throw new IllegalArgumentException("上期前区球号格式错误");
                        }
                    })
                    .collect(java.util.stream.Collectors.toList());
            
            // 解析上期后区球号
            String[] previousBackBallArray = previousBackBalls.split(",");
            if (previousBackBallArray.length != 2) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "上期后区球号必须为2个");
            }
            
            List<Integer> previousBackBallList = java.util.Arrays.stream(previousBackBallArray)
                    .map(s -> {
                        try {
                            int ball = Integer.parseInt(s.trim());
                            if (ball < 1 || ball > 12) {
                                throw new IllegalArgumentException("上期后区球号范围应为1-12");
                            }
                            return ball;
                        } catch (NumberFormatException e) {
                            throw new IllegalArgumentException("上期后区球号格式错误");
                        }
                    })
                    .collect(java.util.stream.Collectors.toList());
            
            // 解析本期前区球号
            String[] currentFrontBallArray = currentFrontBalls.split(",");
            if (currentFrontBallArray.length != 5) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "本期前区球号必须为5个");
            }
            
            List<Integer> currentFrontBallList = java.util.Arrays.stream(currentFrontBallArray)
                    .map(s -> {
                        try {
                            int ball = Integer.parseInt(s.trim());
                            if (ball < 1 || ball > 35) {
                                throw new IllegalArgumentException("本期前区球号范围应为1-35");
                            }
                            return ball;
                        } catch (NumberFormatException e) {
                            throw new IllegalArgumentException("本期前区球号格式错误");
                        }
                    })
                    .collect(java.util.stream.Collectors.toList());
            
            log.info("精推大乐透第三步分析请求：策略={}, 上期前区={}, 上期后区={}, 本期前区={}", 
                    level, previousFrontBallList, previousBackBallList, currentFrontBallList);
            
            // 调用分析算法
            DLTThirdStepResultVO result = backBallAnalysis.analyze(level, previousFrontBallList, 
                    previousBackBallList, currentFrontBallList);
            
            log.info("精推大乐透第三步分析完成，返回{}个结果", result.getResults().size());
            
            return ResultUtils.success(result);
            
        } catch (Exception e) {
            log.error("精推大乐透第三步分析失败", e);
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "分析失败：" + e.getMessage());
        }
    }
    
    /**
     * 精推大乐透第四步分析
     */
    @PostMapping("/fourth-step")
    @Operation(summary = "精推大乐透第四步分析", description = "根据上期前区5个球号、上期后区2个球号、本期前区5个球号和本期后区首球进行第四步分析")
    public ApiResponse<DLTFourthStepResultVO> fourthStepAnalysis(
            @Parameter(description = "策略级别（H-高位/M-中位/L-低位）", required = true)
            @RequestParam String level,
            @Parameter(description = "上期前区球号列表（逗号分隔，如：1,5,12,18,22）", required = true)
            @RequestParam String previousFrontBalls,
            @Parameter(description = "上期后区球号列表（逗号分隔，如：3,7）", required = true)
            @RequestParam String previousBackBalls,
            @Parameter(description = "本期前区球号列表（逗号分隔，如：2,9,16,23,29）", required = true)
            @RequestParam String currentFrontBalls,
            @Parameter(description = "本期后区首球号码", required = true)
            @RequestParam Integer currentBackFirstBall) {
        
        try {
            // 参数验证
            if (!"H".equalsIgnoreCase(level) && !"M".equalsIgnoreCase(level) && !"L".equalsIgnoreCase(level)) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "策略级别必须是H/M/L之一");
            }
            
            if (currentBackFirstBall == null || currentBackFirstBall < 1 || currentBackFirstBall > 12) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "本期后区首球号码范围应为1-12");
            }
            
            // 解析上期前区球号
            String[] previousFrontBallArray = previousFrontBalls.split(",");
            if (previousFrontBallArray.length != 5) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "上期前区球号必须为5个");
            }
            
            List<Integer> previousFrontBallList = java.util.Arrays.stream(previousFrontBallArray)
                    .map(s -> {
                        try {
                            int ball = Integer.parseInt(s.trim());
                            if (ball < 1 || ball > 35) {
                                throw new IllegalArgumentException("上期前区球号范围应为1-35");
                            }
                            return ball;
                        } catch (NumberFormatException e) {
                            throw new IllegalArgumentException("上期前区球号格式错误");
                        }
                    })
                    .collect(java.util.stream.Collectors.toList());
            
            // 解析上期后区球号
            String[] previousBackBallArray = previousBackBalls.split(",");
            if (previousBackBallArray.length != 2) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "上期后区球号必须为2个");
            }
            
            List<Integer> previousBackBallList = java.util.Arrays.stream(previousBackBallArray)
                    .map(s -> {
                        try {
                            int ball = Integer.parseInt(s.trim());
                            if (ball < 1 || ball > 12) {
                                throw new IllegalArgumentException("上期后区球号范围应为1-12");
                            }
                            return ball;
                        } catch (NumberFormatException e) {
                            throw new IllegalArgumentException("上期后区球号格式错误");
                        }
                    })
                    .collect(java.util.stream.Collectors.toList());
            
            // 解析本期前区球号
            String[] currentFrontBallArray = currentFrontBalls.split(",");
            if (currentFrontBallArray.length != 5) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "本期前区球号必须为5个");
            }
            
            List<Integer> currentFrontBallList = java.util.Arrays.stream(currentFrontBallArray)
                    .map(s -> {
                        try {
                            int ball = Integer.parseInt(s.trim());
                            if (ball < 1 || ball > 35) {
                                throw new IllegalArgumentException("本期前区球号范围应为1-35");
                            }
                            return ball;
                        } catch (NumberFormatException e) {
                            throw new IllegalArgumentException("本期前区球号格式错误");
                        }
                    })
                    .collect(java.util.stream.Collectors.toList());
            
            log.info("精推大乐透第四步分析请求：策略={}, 上期前区={}, 上期后区={}, 本期前区={}, 本期后区首球={}", 
                    level, previousFrontBallList, previousBackBallList, currentFrontBallList, currentBackFirstBall);
            
            // 调用分析算法
            DLTFourthStepResultVO result = followBackendBallAnalysis.analyze(level, previousFrontBallList, 
                    previousBackBallList, currentFrontBallList, currentBackFirstBall);
            
            log.info("精推大乐透第四步分析完成，返回{}个结果", result.getResults().size());
            
            return ResultUtils.success(result);
            
        } catch (Exception e) {
            log.error("精推大乐透第四步分析失败", e);
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "分析失败：" + e.getMessage());
        }
    }
}
