package com.emoon.tongue.controller;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import com.emoon.common.core.domain.R;
import com.emoon.common.core.utils.StringUtils;
import com.emoon.tongue.domain.vo.TestDataVo;
import com.emoon.tongue.domain.vo.TongueDiagnosisInfo;
import com.emoon.tongue.domain.vo.TongueDiagnosisDetailVo;
import com.emoon.tongue.domain.vo.TongueImageCheckVo;
import com.emoon.tongue.service.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.ui.Model;

import java.util.*;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 舌诊控制器
 *
 * @author destiny
 * @date 2025-12-09
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/diagnosis")
@CrossOrigin(origins = "*", maxAge = 3600)
@RequiredArgsConstructor
public class DiagnosisController {

    private final ITongueDiagnosisService tongueDiagnosisService;
    private final MinioService minioService;
    private final ITongueImageCheckService tongueImageCheckService;
    private final ITongueAiDiagnosisService tongueAiDiagnosisService;
    private final ILLMService llmService;
    private final ISaveFileService saveFileService;

    // 大模型配置
    @Value("${ai.llm.url}")
    private String llmUrl;

    @Value("${ai.llm.model}")
    private String llmModel;

    @Value("${ai.llm.max-tokens}")
    private Integer llmMaxTokens;

    /**
     * mock 生成一个递增 id，避免每次都一样（方便排查日志）
     */
    private static final AtomicLong MOCK_ID_SEQ = new AtomicLong(1);

    /**
     * 获取舌诊任务详情（内网调用，无需签名验证）
     *
     * @param patientId 患者ID
     * @param projectId 医院编码
     * @return 舌诊任务详情
     */
    @GetMapping("/internal/detail")
    public R<TongueDiagnosisDetailVo> getDiagnosisDetailInternal(@RequestParam String patientId,
                                                                 @RequestParam String projectId) {
        try {
            // 查询舌诊任务详情
            TongueDiagnosisDetailVo detail = tongueDiagnosisService.getDiagnosisDetail(patientId, projectId);
            return R.ok(detail);
        } catch (Exception e) {
            log.error("获取舌诊详情异常", e);
            return R.fail("获取舌诊详情失败：" + e.getMessage());
        }
    }

    /**
     * 获取舌诊任务详情
     *
     * @param patientId 患者ID
     * @param projectId 医院编码
     * @param timestamp 时间戳
     * @param version   版本号
     * @param sign      签名
     * @return 舌诊任务详情
     */
    @GetMapping("/detail")
    public R<TongueDiagnosisDetailVo> getDiagnosisDetail(@RequestParam String patientId,
                                                         @RequestParam String projectId,
                                                         @RequestParam Long timestamp,
                                                         @RequestParam String version,
                                                         @RequestParam String sign) {

        // 验证时间戳（5分钟内有效）
        if (System.currentTimeMillis() - timestamp > 500 * 60 * 1000) {
            return R.fail("请求已过期");
        }

        // 验证签名
        Map<String, Object> params = new HashMap<>();
        params.put("patientId", patientId);
        params.put("projectId", projectId);
        params.put("timestamp", timestamp);
        params.put("version", version);

        if (!validateSign(params, sign)) {
            return R.fail("签名验证失败");
        }

        // 查询舌诊任务详情
        TongueDiagnosisDetailVo detail = tongueDiagnosisService.getDiagnosisDetail(patientId, projectId);
        return R.ok(detail);
    }

    /**
     * 舌诊AI诊断接口
     *
     * @param patientId 患者ID
     * @param projectId 医院编码
     * @param timestamp 时间戳
     * @param version   版本号
     * @param sign      签名
     * @return 任务ID
     */
    @PostMapping("/ai-diagnosis")
    public R<Long> performAiDiagnosis(@RequestParam String patientId,
                                      @RequestParam String projectId,
                                      @RequestParam Long timestamp,
                                      @RequestParam String version,
                                      @RequestParam String sign) {

        // 验证时间戳（5分钟内有效）
        if (System.currentTimeMillis() - timestamp > 500 * 60 * 1000) {
            return R.fail("请求已过期");
        }

        // 验证签名
        Map<String, Object> params = new HashMap<>();
        params.put("patientId", patientId);
        params.put("projectId", projectId);
        params.put("timestamp", timestamp);
        params.put("version", version);

        if (!validateSign(params, sign)) {
            return R.fail("签名验证失败");
        }

        try {
            // 获取记录主键ID作为任务ID
            Long taskId = tongueDiagnosisService.getDiagnosisId(patientId, projectId);

            if (taskId == null) {
                return R.fail("未找到舌诊记录，请先上传舌象图片并通过校验");
            }

            // 异步执行AI诊断
            performAiDiagnosisAsync(taskId, patientId, projectId);

            return R.ok("诊断任务已启动", taskId);
        } catch (Exception e) {
            log.error("舌诊AI诊断异常", e);
            return R.fail("诊断失败：" + e.getMessage());
        }
    }

    /**
     * 舌象图片校验接口
     *
     * @param file      舌象图片文件
     * @param patientId 患者ID
     * @param projectId 医院编码
     * @param timestamp 时间戳
     * @param sign      签名
     * @param version   版本号
     * @param bizParams 业务参数JSON字符串，包含患者信息
     * @return 校验结果
     */
    @PostMapping("/check-image")
    public R<TongueImageCheckVo> checkTongueImage(@RequestParam("file") MultipartFile file,
                                                  @RequestParam String patientId,
                                                  @RequestParam String projectId,
                                                  @RequestParam Long timestamp,
                                                  @RequestParam String sign,
                                                  @RequestParam String version,
                                                  @RequestParam String bizParams) {

        // 验证时间戳（5分钟内有效）
        if (System.currentTimeMillis() - timestamp > 500 * 60 * 1000) {
            return R.fail("请求已过期");
        }

        // 验证签名
        Map<String, Object> params = new HashMap<>();
        params.put("file", file.getOriginalFilename());
        params.put("patientId", patientId);
        params.put("projectId", projectId);
        params.put("timestamp", timestamp);
        params.put("version", version);
        params.put("bizParams", bizParams);

        if (!validateSign(params, sign)) {
            return R.fail("签名验证失败");
        }

        try {
            // 解析bizParams JSON
            Map<String, Object> patientInfo = JSONUtil.parseObj(bizParams);
            Integer patientAge = null;
            Integer patientGender = null;
            String patientChiefComplaint = null;

            try {
                patientAge = (Integer) patientInfo.get("patientAge");
            } catch (Exception e) {
                log.warn("解析patientAge失败，设置为null", e);
            }

            try {
                patientGender = (Integer) patientInfo.get("patientGender");
            } catch (Exception e) {
                log.warn("解析patientGender失败，设置为null", e);
            }

            try {
                patientChiefComplaint = (String) patientInfo.get("patientChiefComplaint");
            } catch (Exception e) {
                log.warn("解析patientChiefComplaint失败，设置为null", e);
            }

            // 上传文件到MinIO
            String fileUrl = minioService.uploadFile(file);
            if (fileUrl == null || fileUrl.isEmpty()) {
                return R.fail("文件上传失败");
            }
            String rawFilePath = saveFileService.uploadFilePath(file);
            String filePath = convertToLocalModelFileUri(rawFilePath);
            log.info("文件已保存至服务器并转换为本地模型路径: patientId={}, projectId={}, fileName={}, rawFilePath={}, filePath={}",
                patientId, projectId, file != null ? file.getOriginalFilename() : null, rawFilePath, filePath);
            if (filePath == null || filePath.isEmpty()) {
                return R.fail("文件保存至服务器失败");
            }

            // 调用大模型服务校验舌象图片
            TongueImageCheckVo checkResult = tongueImageCheckService.checkTongueImage(fileUrl);

            if (checkResult.getErrorCode() != null && checkResult.getErrorCode() == 0) {
                // 图片符合要求，保存上传记录
                boolean success = tongueDiagnosisService.handleTongueImageUpload(
                    fileUrl, filePath, patientId, projectId, patientAge, patientGender, patientChiefComplaint);

                if (!success) {
                    return R.fail("上传记录保存失败");
                }

                return R.ok("图片符合要求", checkResult);
            } else {
                // 图片不符合要求，返回对应的错误规则详情
                return R.fail(checkResult.getErrorType(), checkResult);
            }
        } catch (Exception e) {
            log.error("舌象图片校验异常", e);
            return R.fail("校验失败：" + e.getMessage());
        }
    }

    /**
     * 生成测试数据接口
     *
     * @param file 舌象图片文件（可选）
     * @return 测试数据
     */
    @PostMapping("/generate-test-data")
    public R<TestDataVo> generateTestData(@RequestParam(value = "file", required = false) MultipartFile file) {
        TestDataVo testData = new TestDataVo();

        try {
            // 随机生成患者ID
            String dateStr = String.valueOf(System.currentTimeMillis()).substring(0, 8);
            int randomNum = new Random().nextInt(999) + 1;
            testData.setPatientId("GH" + dateStr + String.format("%03d", randomNum));

            // 随机生成医院编码
            String[] hospitalCodes = {"HOSP001", "HOSP002", "HOSP003", "HOSP004", "HOSP005"};
            testData.setProjectId(hospitalCodes[new Random().nextInt(hospitalCodes.length)]);

            // 当前时间戳
            testData.setTimestamp(System.currentTimeMillis());

            // 固定版本号
            testData.setVersion("v1.0.0");

            // 随机生成患者信息
            testData.setPatientAge(new Random().nextInt(50) + 18); // 18-67岁
            testData.setPatientGender(new Random().nextInt(2) + 1); // 1或2

            String[] complaints = {
                "口干舌燥，睡眠不佳",
                "胃胀胃痛，食欲不振",
                "头晕乏力，精神不振",
                "咳嗽有痰，胸闷气短",
                "腰膝酸软，畏寒怕冷",
                "心烦易怒，失眠多梦",
                "消化不良，大便不成形",
                "面色苍白，手脚冰凉"
            };
            testData.setPatientChiefComplaint(complaints[new Random().nextInt(complaints.length)]);

            // 生成bizParams JSON字符串
            Map<String, Object> patientInfo = new HashMap<>();
            patientInfo.put("patientAge", testData.getPatientAge());
            patientInfo.put("patientGender", testData.getPatientGender());
            patientInfo.put("patientChiefComplaint", testData.getPatientChiefComplaint());
            testData.setBizParams(JSONUtil.toJsonStr(patientInfo));

            // 设置文件名：如果传入了文件则使用originalName，否则随机生成
            if (file != null && !file.isEmpty() && file.getOriginalFilename() != null) {
                testData.setFileName(file.getOriginalFilename());
            } else {
                String[] extensions = {".jpg", ".jpeg", ".png", ".bmp"};
                String extension = extensions[new Random().nextInt(extensions.length)];
                testData.setFileName("tongue_" + System.currentTimeMillis() + extension);
            }

            // 生成签名
            Map<String, Object> signParams = new HashMap<>();
            signParams.put("file", testData.getFileName());
            signParams.put("patientId", testData.getPatientId());
            signParams.put("projectId", testData.getProjectId());
            signParams.put("timestamp", testData.getTimestamp());
            signParams.put("bizParams", testData.getBizParams());
            signParams.put("version", testData.getVersion());

            String generatedSign = generateSign(signParams);
            testData.setSign(generatedSign);

            return R.ok("测试数据生成成功", testData);
        } catch (Exception e) {
            log.error("生成测试数据异常", e);
            return R.fail("生成测试数据失败：" + e.getMessage());
        }
    }

    /**
     * 生成签名
     *
     * @param params 参数Map
     * @return MD5签名
     */
    private String generateSign(Map<String, Object> params) {
        // 按照ASCII码排序参数
        List<String> sortedKeys = new ArrayList<>(params.keySet());
        Collections.sort(sortedKeys);

        // 拼接参数字符串
        StringBuilder sb = new StringBuilder();
        for (String key : sortedKeys) {
            Object value = params.get(key);
            if (value != null && StringUtils.isNotEmpty(value.toString())) {
                sb.append(key).append("=").append(value).append("&");
            }
        }

        // 移除最后一个&
        if (!sb.isEmpty()) {
            sb.deleteCharAt(sb.length() - 1);
        }

        // MD5加密并转为大写
        return SecureUtil.md5(sb.toString()).toUpperCase();
    }

    /**
     * 异步执行AI诊断
     *
     * @param taskId     任务ID（记录主键ID）
     * @param patientId  患者ID
     * @param projectId  医院编码
     */
    @Async("tongueDiagnosisExecutor")
    public void performAiDiagnosisAsync(Long taskId, String patientId, String projectId) {
        log.info("开始异步执行AI诊断，任务ID: {}, 患者ID: {}", taskId, patientId);
        try {
            // 模拟AI诊断处理时间，随机睡眠1-10秒
            Random random = new Random();
            int sleepSeconds = random.nextInt(10) + 1;
            log.info("AI诊断预计耗时: {} 秒", sleepSeconds);
            TimeUnit.SECONDS.sleep(sleepSeconds);

            // 生成AI诊断结果
            TongueDiagnosisInfo diagnosisResult = tongueAiDiagnosisService.performDiagnosis(patientId, projectId);

            if (diagnosisResult == null) {
                log.error("AI诊断结果为空，任务ID: {}", taskId);
            }
            // 将诊断结果转换为JSON字符串
            String diagnosisJson = JSONUtil.toJsonStr(diagnosisResult);
            // 更新数据库中的诊断结果
            boolean success = tongueDiagnosisService.updateAiDiagnosisResult(taskId, diagnosisJson);
            log.info("AI诊断结果: {}, 任务ID: {}，是否保存成功: {}", diagnosisJson, taskId, success);
        } catch (InterruptedException e) {
            log.error("AI诊断任务被中断，任务ID: {}", taskId, e);
            Thread.currentThread().interrupt();
        } catch (Exception e) {
            log.error("AI诊断异步执行异常，任务ID: {}", taskId, e);
        }
    }

    /**
     * 调用大模型API接口
     *
     * @param request 请求体，包含prompt字段
     * @return 模型响应结果
     */
    @PostMapping("/llm-call")
    public R<String> callLlm(@RequestBody Map<String, String> request) {
        log.info("收到LLM调用请求，参数: {}", request);

        try {
            String prompt = request.get("prompt");
            if (StringUtils.isEmpty(prompt)) {
                return R.fail("提示词不能为空");
            }

            log.info("开始调用LLM服务，prompt: {}", prompt.substring(0, Math.min(100, prompt.length())) + "...");

            String result = llmService.callLLM(prompt, llmUrl, llmModel, llmMaxTokens);

            log.info("LLM调用成功，返回结果长度: {}", result != null ? result.length() : 0);
            return R.ok(result);
        } catch (Exception e) {
            log.error("调用大模型API失败", e);
            return R.fail("调用失败: " + e.getMessage());
        }
    }

    /**
     * 生成签名接口（供H5页面调用）
     *
     * @param params 参数Map
     * @return 生成的签名
     */
    @PostMapping("/generate-sign")
    public R<String> generateSignForFrontend(@RequestBody Map<String, Object> params) {
        try {
            String sign = generateSign(params);
            return R.ok("签名生成成功", sign);
        } catch (Exception e) {
            log.error("生成签名异常", e);
            return R.fail("生成签名失败：" + e.getMessage());
        }
    }


    /**
     * 验证签名
     *
     * @param params 参数Map
     * @param sign   待验证签名
     * @return 是否验证通过
     */
    private boolean validateSign(Map<String, Object> params, String sign) {
        String generatedSign = generateSign(params);
        log.info("生成签名: {}, 待验证签名: {}", generatedSign, sign);
        return generatedSign.equals(sign);
    }

    /**
     * 将落盘服务返回的 filePath（例如：/ruoyi/file-downloads/xxx.jpg）
     * 转换为本地模型可直接读取的 file:// URI（例如：file:///home/gansu/gansu/shetou_picture/xxx.jpg）
     */
    private String convertToLocalModelFileUri(String rawFilePath) {
        if (rawFilePath == null) {
            return null;
        }
        String s = rawFilePath.trim();
        if (s.isEmpty()) {
            return null;
        }

        // 已经是 file://... 形式就直接返回
        if (s.startsWith("file://")) {
            return s;
        }

        // 取最后的文件名（兼容 / 和 \）
        int idx1 = s.lastIndexOf('/');
        int idx2 = s.lastIndexOf('\\');
        int idx = Math.max(idx1, idx2);
        String fileName = idx >= 0 ? s.substring(idx + 1) : s;
        if (fileName.isEmpty()) {
            return null;
        }

        // 固定替换为模型服务器本地目录
        return "file:///home/gansu/gansu/shetou_picture/" + fileName;
    }

    /**
     * 本地模型 Mock：返回固定的 ChatCompletions 结构（用于本地模型未训练完时联调整体流程）
     *
     * <p>注意：该接口返回的是“原始 chat.completion JSON”，不会包一层 R，否则本地 provider 无法解析 choices。</p>
     */
    @PostMapping("/mock/local-chat-completions")
    public Map<String, Object> mockLocalChatCompletions(@RequestBody(required = false) Map<String, Object> request) {
        String model = request != null && request.get("model") != null ? String.valueOf(request.get("model")) : "/home/gansu/output_sft_qwen3_2B";
        long created = System.currentTimeMillis() / 1000;

        Map<String, Object> message = new HashMap<>();
        message.put("role", "assistant");
        message.put("content",
            "病人舌苔呈现的现象为：厚苔, 润苔, 腻苔, 裂纹舌, 青红舌, 黄, 齿痕舌。\n" +
                "诊断为：脾肾不固证。\n" +
                "处方：中药14付,每日两次,自煎 200ml,分2次中药口服:黑顺片 3g 先煎,红参 3g 另煎,干姜 3g,砂仁 9g 后下,酒大黄 3g,焦槟榔 9g,乌药 9g,麸炒枳壳 15g,醋香附 9g,沉香 3g 后下,檀香 5g,木香 6g,制吴茱萸 3g,丹参 15g,连翘 15g。"
        );
        message.put("refusal", null);
        message.put("annotations", null);
        message.put("audio", null);
        message.put("function_call", null);
        message.put("tool_calls", Collections.emptyList());
        message.put("reasoning_content", null);

        Map<String, Object> choice = new HashMap<>();
        choice.put("index", 0);
        choice.put("message", message);
        choice.put("logprobs", null);
        choice.put("finish_reason", "stop");
        choice.put("stop_reason", null);
        choice.put("token_ids", null);

        Map<String, Object> usage = new HashMap<>();
        usage.put("prompt_tokens", 86);
        usage.put("total_tokens", 274);
        usage.put("completion_tokens", 188);
        usage.put("prompt_tokens_details", null);

        Map<String, Object> resp = new HashMap<>();
        resp.put("id", "chatcmpl-mock-" + MOCK_ID_SEQ.getAndIncrement());
        resp.put("object", "chat.completion");
        resp.put("created", created);
        resp.put("model", model);
        resp.put("choices", List.of(choice));
        resp.put("service_tier", null);
        resp.put("system_fingerprint", null);
        resp.put("usage", usage);
        resp.put("prompt_logprobs", null);
        resp.put("prompt_token_ids", null);
        resp.put("kv_transfer_params", null);
        return resp;
    }
}
