package com.emoon.modules.chat.controller;

import com.emoon.chat.domain.dto.PatientRecordWithQCResultDTO;
import com.emoon.chat.domain.dto.RecordDetailItemDTO;
import com.emoon.chat.service.IPatientRecordService;
import com.emoon.common.mybatis.core.page.PageQuery;
import com.emoon.common.mybatis.core.page.TableDataInfo;
import com.emoon.common.satoken.utils.LoginHelper;
import jakarta.annotation.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;

/**
 * 患者病历数据获取接口
 */
@RestController
@RequestMapping("/patientRecord")
public class PatientDataController {

    @Resource
    private IPatientRecordService patientRecordService;  // 面向接口编程

    /**
     * GET /api/patient/fetch
     * 手动触发：从外部接口拉取患者病历数据并保存
     */
    @GetMapping("/test")
    public ResponseEntity<String> fetchPatientData() {
        try {
            patientRecordService.fetchAndSavePatientTest();
            return ResponseEntity.ok("✅ 数据拉取与保存完成");
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body("❌ 失败：" + e.getMessage());
        }
    }

    @PostMapping("/fetch")
    public ResponseEntity<String> fetchPatientData(@RequestBody Map<String, String> params) {
        try {
            String startDate = params.get("startDate");
            String endDate = params.get("endDate");

            if (startDate == null || endDate == null) {
                return ResponseEntity.badRequest().body("❌ 缺少参数：startDate 或 endDate");
            }

            // 调用服务层，传入参数
            patientRecordService.fetchAndSavePatientData(startDate, endDate);

            return ResponseEntity.ok("✅ 数据拉取与保存完成");
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body("❌ 失败：" + e.getMessage());
        }
    }

    /**
     * 获取的病历列表
     */
    @GetMapping("/qcRecords")
    public TableDataInfo<PatientRecordWithQCResultDTO> patientRecordWithQCResultList(
        PageQuery pageQuery,
        @RequestParam(required = false) String recordId,
        @RequestParam(required = false) String admissionNo,
        @RequestParam(required = false) String patientName,
        @RequestParam(required = false) String admissionDept,
        @RequestParam(required = false) String status,
        @RequestParam(required = false) String attendingDoctor,
        @RequestParam(required = false) String qcStartDate,
        @RequestParam(required = false) String qcEndDate,
        @RequestParam(required = false) String viewed
    ) {
        Long userId = LoginHelper.getUserId();
        return patientRecordService.patientRecordList(pageQuery, recordId, admissionNo, patientName,
            admissionDept, status, attendingDoctor, qcStartDate, qcEndDate, viewed, userId);
    }

    /**
     * 获取病历详情（含所有类型内容 + 质控结果）
     */
    @PostMapping("/detail")
    public ResponseEntity<Map<String, Object>> getDetail(@RequestBody Map<String, Object> request) {
        Object idObj = request.get("id");
        String id = idObj != null ? idObj.toString().trim() : null;

        if (id == null || id.isEmpty()) {
            Map<String, Object> error = new HashMap<>();
            error.put("code", 400);
            error.put("msg", "缺少必要参数 id");
            error.put("total", 0);
            error.put("rows", Collections.emptyList());
            return ResponseEntity.badRequest().body(error);
        }

        List<RecordDetailItemDTO> detailList = patientRecordService.getDetailListById(id);

        LocalDateTime latestQcEndTime = detailList.stream()
            .map(RecordDetailItemDTO::getQcEndTime)
            .filter(Objects::nonNull)
            .max(LocalDateTime::compareTo)
            .orElse(null);
        Long userId = LoginHelper.getUserId();
        boolean viewed = userId != null && patientRecordService.isRecordViewedByUser(id, userId);

        Map<String, Object> result = new HashMap<>();
        result.put("total", detailList.size());
        result.put("rows", detailList);
        result.put("latestQcEndTime", latestQcEndTime);
        result.put("viewed", viewed);
        result.put("code", 200);
        result.put("msg", "查询成功");

        return ResponseEntity.ok(result);
    }

    @PostMapping("/viewStatus")
    public ResponseEntity<Map<String, Object>> updateViewStatus(@RequestBody Map<String, Object> request) {
        String patientRecordId = Optional.ofNullable(request.get("patientRecordId"))
            .map(Object::toString)
            .map(String::trim)
            .orElse(null);
        Object viewedObj = request.get("viewed");
        boolean targetViewed = viewedObj != null && Boolean.parseBoolean(viewedObj.toString());

        Map<String, Object> resp = new HashMap<>();
        if (patientRecordId == null || patientRecordId.isEmpty()) {
            resp.put("code", 400);
            resp.put("msg", "缺少必要参数 patientRecordId");
            return ResponseEntity.badRequest().body(resp);
        }

        Long userId = LoginHelper.getUserId();
        if (userId == null) {
            resp.put("code", 401);
            resp.put("msg", "未登录或登录已失效");
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(resp);
        }

        boolean success;
        if (targetViewed) {
            success = patientRecordService.markRecordAsViewed(patientRecordId, userId);
        } else {
            success = patientRecordService.cancelRecordViewed(patientRecordId, userId);
        }

        boolean latestStatus = patientRecordService.isRecordViewedByUser(patientRecordId, userId);
        resp.put("viewed", latestStatus);

        if (success) {
            resp.put("code", 200);
            resp.put("msg", latestStatus ? "已标记为已查看" : "已取消查看标记");
            return ResponseEntity.ok(resp);
        } else {
            resp.put("code", 500);
            resp.put("msg", "操作失败，请稍后重试");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(resp);
        }
    }

    @PostMapping("/saveQcOpinion")
    public Map<String, Object> saveQcOpinion(@RequestBody Map<String, String> request) {
        String patientRecordId = request.get("patientRecordId");
        String qcReviewComments = request.get("qcReviewComments");
        String qcName = request.get("qcName");
        String qcType = request.get("type"); // ✅ 获取前端传过来的 type

        boolean success = patientRecordService.saveQcOpinion(patientRecordId, qcReviewComments, qcName, qcType);

        Map<String, Object> resp = new HashMap<>();
        if (success) {
            resp.put("code", 200);
            resp.put("msg", "操作成功");
        } else {
            resp.put("code", 500);
            resp.put("msg", "质控意见保存失败");
        }
        resp.put("data", null);
        return resp;
    }

}
