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.ITongueAiDiagnosisService;
import com.emoon.tongue.service.ITongueDiagnosisService;
import com.emoon.tongue.service.ITongueImageCheckService;
import com.emoon.tongue.service.MinioService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

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

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

    private final ITongueDiagnosisService tongueDiagnosisService;
    private final MinioService minioService;
    private final ITongueImageCheckService tongueImageCheckService;
    private final ITongueAiDiagnosisService tongueAiDiagnosisService;

    /**
     * 获取舌诊任务详情
     *
     * @param regNumber 挂号单号
     * @param projectId 医院编码
     * @param timestamp 时间戳
     * @param version   版本号
     * @param sign      签名
     * @return 舌诊任务详情
     */
    @GetMapping("/detail")
    public R<TongueDiagnosisDetailVo> getDiagnosisDetail(@RequestParam String regNumber,
                                                         @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("regNumber", regNumber);
        params.put("projectId", projectId);
        params.put("timestamp", timestamp);
        params.put("version", version);

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

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

    /**
     * 舌诊AI诊断接口
     *
     * @param regNumber 挂号单号
     * @param projectId 医院编码
     * @param timestamp 时间戳
     * @param version   版本号
     * @param sign      签名
     * @return 任务ID
     */
    @PostMapping("/ai-diagnosis")
    public R<Long> performAiDiagnosis(@RequestParam String regNumber,
                                      @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("regNumber", regNumber);
        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(regNumber, projectId);

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

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

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

    /**
     * 舌象图片校验接口
     *
     * @param file      舌象图片文件
     * @param regNumber 挂号单号
     * @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 regNumber,
                                                  @RequestParam String projectId,
                                                  @RequestParam Long timestamp,
                                                  @RequestParam String sign,
                                                  @RequestParam String version,
                                                  @RequestParam String bizParams) {
        log.info("舌象图片校验请求参数：file={}, regNumber={}, projectId={}, timestamp={}, sign={}, version={}, bizParams={}",
            file.getOriginalFilename(), regNumber, projectId, timestamp, sign, version, 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("regNumber", regNumber);
        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("文件上传失败");
            }

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

            if (checkResult.getErrorCode() != null && checkResult.getErrorCode() == 0) {
                // 图片符合要求，保存上传记录
                boolean success = tongueDiagnosisService.handleTongueImageUpload(
                    fileUrl, regNumber, 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();
        log.info("generate-test-data 请求参数: {}", file.getOriginalFilename());
        try {
            // 随机生成挂号单号
            String dateStr = String.valueOf(System.currentTimeMillis()).substring(0, 8);
            int randomNum = new Random().nextInt(999) + 1;
            testData.setRegNumber("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("regNumber", testData.getRegNumber());
            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 regNumber 挂号单号
     * @param projectId 医院编码
     */
    @Async("tongueDiagnosisExecutor")
    public void performAiDiagnosisAsync(Long taskId, String regNumber, String projectId) {
        log.info("开始异步执行AI诊断，任务ID: {}, 挂号单号: {}", taskId, regNumber);
        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(regNumber, 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);
        }
    }

    /**
     * 验证签名
     *
     * @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);
    }
}
