package org.example.controller;

import org.example.entity.PageResult;
import org.example.entity.Patient;
import org.example.entity.PatientDiagnosis;
import org.example.entity.PatientOrder;
import org.example.entity.PatientCharge;
import org.example.entity.PatientExam;
import org.example.entity.PatientTest;
import org.example.entity.PatientTestItem;
import org.example.service.PatientService;
import org.example.service.PatientDiagnosisService;
import org.example.service.PatientOrderService;
import org.example.service.PatientChargeService;
import org.example.service.PatientExamService;
import org.example.service.PatientTestService;
import org.example.service.PatientTestItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 患者控制器
 */
@RestController
@RequestMapping("/api/patient")
public class PatientController {

    @Autowired
    private PatientService patientService;

    @Autowired
    private PatientDiagnosisService patientDiagnosisService;

    @Autowired
    private PatientOrderService patientOrderService;

    @Autowired
    private PatientChargeService patientChargeService;

    @Autowired
    private PatientExamService patientExamService;

    @Autowired
    private PatientTestService patientTestService;

    @Autowired
    private PatientTestItemService patientTestItemService;

    /**
     * 获取页面初始化数据（合并接口，减少请求次数，支持分页）
     */
    @GetMapping("/init-data")
    public Map<String, Object> initData(
            @RequestParam(required = false, defaultValue = "1") Integer page,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("data", patientService.getInitData(page, pageSize));
        return result;
    }

    /**
     * 查询患者列表（支持分页）
     */
    @GetMapping("/list")
    public Map<String, Object> list(
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String deptCode,
            @RequestParam(required = false) String wardCode,
            @RequestParam(required = false) String roomNo,
            @RequestParam(required = false) String bedNo,
            @RequestParam(required = false) String inpatientNo,
            @RequestParam(required = false) String nurseLevel,
            @RequestParam(required = false) String inpatientStatus,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date admissionDateStart,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date admissionDateEnd,
            @RequestParam(required = false, defaultValue = "1") Integer page,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        Map<String, Object> result = new HashMap<>();
        List<Patient> list = patientService.findList(name, deptCode, wardCode, roomNo, bedNo,
                inpatientNo, nurseLevel, inpatientStatus, admissionDateStart, admissionDateEnd);
        // 分页处理
        PageResult<Patient> pageResult = PageResult.of(list, page, pageSize);
        result.put("code", 200);
        result.put("data", pageResult);
        return result;
    }

    /**
     * 获取所属科室列表（用于下拉框）
     */
    @GetMapping("/dept-list")
    public Map<String, Object> deptList() {
        Map<String, Object> result = new HashMap<>();
        List<String> list = patientService.findAllDeptCode();
        result.put("code", 200);
        result.put("data", list);
        return result;
    }

    /**
     * 根据科室获取病区列表（用于联动下拉框）
     */
    @GetMapping("/ward-list")
    public Map<String, Object> wardList(@RequestParam(required = false) String deptCode) {
        Map<String, Object> result = new HashMap<>();
        List<String> list = patientService.findWardsByDept(deptCode);
        result.put("code", 200);
        result.put("data", list);
        return result;
    }

    /**
     * 根据病区获取房间号列表（用于联动下拉框）
     */
    @GetMapping("/room-list")
    public Map<String, Object> roomList(@RequestParam(required = false) String wardCode) {
        Map<String, Object> result = new HashMap<>();
        List<String> list = patientService.findRoomsByWard(wardCode);
        result.put("code", 200);
        result.put("data", list);
        return result;
    }

    /**
     * 根据房间号获取床位号列表（用于联动下拉框）
     */
    @GetMapping("/bed-list")
    public Map<String, Object> bedList(@RequestParam(required = false) String roomNo) {
        Map<String, Object> result = new HashMap<>();
        List<String> list = patientService.findBedsByRoom(roomNo);
        result.put("code", 200);
        result.put("data", list);
        return result;
    }

    /**
     * 获取在院状态列表（用于下拉框）
     */
    @GetMapping("/inpatient-status-list")
    public Map<String, Object> inpatientStatusList() {
        Map<String, Object> result = new HashMap<>();
        List<String> list = patientService.findAllInpatientStatus();
        result.put("code", 200);
        result.put("data", list);
        return result;
    }

    /**
     * 获取护理级别列表（用于下拉框）
     */
    @GetMapping("/nurse-level-list")
    public Map<String, Object> nurseLevelList() {
        Map<String, Object> result = new HashMap<>();
        List<String> list = patientService.findAllNurseLevel();
        result.put("code", 200);
        result.put("data", list);
        return result;
    }

    /**
     * 获取患者详情
     */
    @GetMapping("/detail/{id}")
    public Map<String, Object> detail(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        Patient patient = patientService.findById(id);
        if (patient != null) {
            result.put("code", 200);
            result.put("data", patient);
        } else {
            result.put("code", 404);
            result.put("message", "患者不存在");
        }
        return result;
    }

    /**
     * 保存患者
     */
    @PostMapping("/save")
    public Map<String, Object> save(@RequestBody Patient patient) {
        Map<String, Object> result = new HashMap<>();
        try {
            patientService.save(patient);
            result.put("code", 200);
            result.put("message", "保存成功");
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "保存失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 删除患者
     */
    @DeleteMapping("/delete/{id}")
    public Map<String, Object> delete(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        try {
            patientService.deleteById(id);
            result.put("code", 200);
            result.put("message", "删除成功");
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "删除失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 获取患者诊断信息列表（通过患者ID查询）
     */
    @GetMapping("/diagnosis/{patientId}")
    public Map<String, Object> getDiagnosisList(@PathVariable Long patientId) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<PatientDiagnosis> list = patientDiagnosisService.findByPatientId(patientId);
            result.put("code", 200);
            result.put("data", list);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "获取诊断信息失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 获取患者诊断信息列表（通过身份证号查询）
     */
    @GetMapping("/diagnosis/idcard/{idCard}")
    public Map<String, Object> getDiagnosisListByIdCard(@PathVariable String idCard) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<PatientDiagnosis> list = patientDiagnosisService.findByIdCard(idCard);
            result.put("code", 200);
            result.put("data", list);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "获取诊断信息失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 获取患者医嘱信息列表（通过患者ID查询）
     */
    @GetMapping("/orders/{patientId}")
    public Map<String, Object> getOrderList(@PathVariable Long patientId) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<PatientOrder> list = patientOrderService.findByPatientId(patientId);
            result.put("code", 200);
            result.put("data", list);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "获取医嘱信息失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 获取患者费用信息列表（通过患者ID查询）
     */
    @GetMapping("/charges/{patientId}")
    public Map<String, Object> getChargeList(@PathVariable Long patientId) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<PatientCharge> list = patientChargeService.findByPatientId(patientId);
            result.put("code", 200);
            result.put("data", list);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "获取费用信息失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 获取患者检查报告列表（通过患者ID查询）
     */
    @GetMapping("/exams/{patientId}")
    public Map<String, Object> getExamList(@PathVariable Long patientId) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<PatientExam> list = patientExamService.findByPatientId(patientId);
            result.put("code", 200);
            result.put("data", list);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "获取检查报告失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 获取患者检验报告列表（通过患者表ID查询）
     */
    @GetMapping("/tests/{patientId}")
    public Map<String, Object> getTestList(@PathVariable Long patientId) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<PatientTest> list = patientTestService.findByPatientTableId(patientId);
            result.put("code", 200);
            result.put("data", list);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "获取检验报告失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 获取检验报告项目明细列表（通过检验报告ID查询）
     */
    @GetMapping("/test-items/{testId}")
    public Map<String, Object> getTestItemList(@PathVariable Long testId) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<PatientTestItem> list = patientTestItemService.findByTestId(testId);
            result.put("code", 200);
            result.put("data", list);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "获取检验项目明细失败：" + e.getMessage());
        }
        return result;
    }
}
