package com.eitc.patient.controller;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.eitc.common.annotation.Log;
import com.eitc.common.constant.HttpStatus;
import com.eitc.common.core.controller.BaseController;
import com.eitc.common.core.domain.AjaxResult;
import com.eitc.common.core.page.PageDomain;
import com.eitc.common.core.page.TableDataInfo;
import com.eitc.common.core.page.TableSupport;
import com.eitc.common.enums.BusinessType;
import com.eitc.common.utils.PatientBaseUtil;
import com.eitc.common.utils.PdfUtil;
import com.eitc.common.utils.bean.BeanUtils;
import com.eitc.patient.domain.DiagnosisManage;
import com.eitc.patient.domain.DiagnosisTypeTemplate;
import com.eitc.patient.domain.MedicalHistory;
import com.eitc.patient.domain.MedicalRecord;
import com.eitc.patient.domain.MedicalRecordDetails;
import com.eitc.patient.domain.Patient;
import com.eitc.patient.domain.ProtocolTemplate;
import com.eitc.patient.dto.DiagnosisTypeTemplateDto;
import com.eitc.patient.dto.MedicalRecordHistoryDto;
import com.eitc.patient.dto.MedicalRecordListDto;
import com.eitc.patient.dto.PatientTeethInfoDto;
import com.eitc.patient.enums.MedicalHistoryDiseaseSourceEnum;
import com.eitc.patient.enums.MedicalHistoryDiseaseTypeEnum;
import com.eitc.patient.param.MedicalRecordListParam;
import com.eitc.patient.param.MedicalRecordParam;
import com.eitc.patient.param.MedicalRecordSaveParam;
import com.eitc.patient.service.IDiagnosisManageService;
import com.eitc.patient.service.IDiagnosisTypeTemplateService;
import com.eitc.patient.service.IMedicalHistoryService;
import com.eitc.patient.service.IMedicalRecordDetailsService;
import com.eitc.patient.service.IMedicalRecordService;
import com.eitc.patient.service.IPatientService;
import com.eitc.patient.service.IProtocolTemplateService;
import com.eitc.patient.vo.MedicalRecordListVO;
import com.eitc.patient.vo.MedicalRecordNoteVO;
import com.eitc.patient.vo.MedicalRecordToPdf;
import com.eitc.patient.vo.MedicalRecordToothVO;
import com.eitc.system.utils.UserCacheUtil;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * MedicalRecordController
 *
 * @author mtx
 * @date: 2024/05/17 15:52
 */
@Api(tags = "病例")
@RestController
@RequestMapping("/patient/medical-record")
@Slf4j
public class MedicalRecordController extends BaseController {

    @Resource
    private IMedicalRecordService medicalRecordService;
    @Resource
    private IMedicalRecordDetailsService medicalRecordDetailsService;
    @Resource
    private IMedicalHistoryService medicalHistoryService;
    @Resource
    private IDiagnosisTypeTemplateService diagnosisTypeTemplateService;
    @Resource
    private IDiagnosisManageService diagnosisManageService;
    @Resource
    private IPatientService patientService;
    @Resource
    private IProtocolTemplateService protocolTemplateService;

    @Resource
    private FreeMarkerConfigurer freeMarkerConfigurer;

    /**
     * 将HTML格式的病历模板转换为PDF格式。
     * 此方法接收一个病历模板的视图对象，经过处理后，使用Freemarker模板引擎将HTML内容渲染，
     * 最后通过响应对象将渲染后的PDF内容发送给客户端。
     *
     * @param vo       包含病历详细信息和模板数据的视图对象。
     * @param response HTTP响应对象，用于向客户端发送PDF内容。
     * @throws IOException       如果处理过程中发生IO异常。
     * @throws TemplateException 如果Freemarker模板处理过程中发生异常。
     */
    @PostMapping(value = "/html2Pdf")
    @ApiOperation("打印病历")
    public void html2Pdf(@RequestBody MedicalRecordToPdf vo, HttpServletResponse response) throws IOException, TemplateException {
        // 准备Freemarker模板渲染所需的参数。
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("companyName", UserCacheUtil.getClinicName() + "口腔科病历");
        paramMap.put("patient", vo);

        // 使用Freemarker模板引擎渲染HTML模板。
        Writer out = new StringWriter();
        //获取模板地址
        Template template = freeMarkerConfigurer.getConfiguration().getTemplate("medical-record.html");
        template.process(paramMap, out);
        out.flush();
        out.close();
        String templateContent = out.toString();

        // 设置响应头，以便客户端可以接收PDF内容。
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/pdf");
        String fileName = System.currentTimeMillis() + ".pdf";
        response.setHeader("Content-Disposition", "filename=" + new String(fileName.getBytes(), StandardCharsets.UTF_8));

        // 调用PDF工具类，将渲染后的HTML内容转换为PDF，并通过响应对象发送给客户端。
        PdfUtil.html2Pdf(templateContent, response);
    }


    /**
     * 根据病历ID查询病历信息。
     *
     * @param medicalRecordId 病历ID。
     * @return 返回病历详情的Ajax结果。
     * @throws ParseException 如果解析日期出错。
     */
    @GetMapping("/findMedicalInfo")
    @ApiOperation("打印病历详情")
    public AjaxResult findMedicalInfo(String medicalRecordId, String protocolTemplateId) throws ParseException {
        MedicalRecordToPdf mrt = new MedicalRecordToPdf();
        // 根据病历ID查询病历信息
        MedicalRecord medicalRecord = medicalRecordService.getById(medicalRecordId);
        // 检查病历是否存在
        if (Objects.nonNull(medicalRecord)) {
            // 获取患者ID
            String patientId = medicalRecord.getPatientId();
            // 根据患者ID查询患者信息
            Patient patient = patientService.getById(patientId);
            // 检查患者信息是否存在
            if (Objects.nonNull(patient)) {
                // 将患者信息复制到病历模板VO中
                BeanUtils.copyProperties(patient, mrt);
                // 根据身份证号计算患者年龄
                mrt.setAge(PatientBaseUtil.findAge(patient.getIdentificationCard()));
            }

            mrt.setChiefComplaintContent(medicalRecord.getChiefComplaintContent());
            mrt.setPresentIllnessContent(medicalRecord.getPresentIllnessContent());
            mrt.setInspectContent(medicalRecord.getInspectContent());
            mrt.setTreatmentPlanningContent(medicalRecord.getTreatmentPlanningContent());
            mrt.setDisposeContent(medicalRecord.getDisposeContent());
            mrt.setDiagnosisContent(medicalRecord.getDiagnosisContent());
            mrt.setNoteContent(medicalRecord.getNoteContent());

            List<MedicalHistory> histories = medicalHistoryService.list(Wrappers.<MedicalHistory>lambdaQuery().eq(MedicalHistory::getPatientId, patientId));

            if (CollectionUtils.isNotEmpty(histories)) {
                mrt.setAllergyHistory(histories.stream().filter(l -> MedicalHistoryDiseaseTypeEnum.ALLERGY_HISTORY.getCode().equals(l.getDiseaseType()))
                        .map(MedicalHistory::getDiseaseContent).collect(Collectors.joining(",")));
                mrt.setPastHistory(histories.stream().filter(l -> MedicalHistoryDiseaseTypeEnum.PAST_HISTORY.getCode().equals(l.getDiseaseType()))
                        .map(MedicalHistory::getDiseaseContent).collect(Collectors.joining(",")));
                mrt.setFamilyHistory(histories.stream().filter(l -> MedicalHistoryDiseaseTypeEnum.FAMILY_HISTORY.getCode().equals(l.getDiseaseType()))
                        .map(MedicalHistory::getDiseaseContent).collect(Collectors.joining(",")));
            }
        }
        mrt.setCompanyName(UserCacheUtil.getClinicName() + "口腔科病历");

        ProtocolTemplate protocolTemplate = protocolTemplateService.getById(protocolTemplateId);
        if (Objects.nonNull(protocolTemplate)) {
            mrt.setContent(protocolTemplate.getProtocolTemplateContent());
        }
        // 返回处理结果
        return success(mrt);
    }

    /**
     * 查询病历
     */
    @GetMapping("/list")
    @ApiOperation("查询病历")
    public AjaxResult list(MedicalRecordListParam medicalRecord) {
        LambdaQueryWrapper<MedicalRecord> wrapper = Wrappers.<MedicalRecord>lambdaQuery()
                .eq(MedicalRecord::getPatientId, medicalRecord.getPatientId())
                .orderByDesc(MedicalRecord::getCreateDate);

        Long queryScope = medicalRecord.getQueryScope();
        if (Objects.nonNull(queryScope)) {
            LocalDateTime dateTime = LocalDateTime.now().minusMonths(queryScope);
            wrapper.ge(MedicalRecord::getCreateDate, dateTime);
        }
        List<MedicalRecord> list = medicalRecordService.list(wrapper);

        List<MedicalRecordListVO> voList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(list)) {
            for (MedicalRecord record : list) {
                voList.add(getMedicalRecordListVO(record));
            }
        }

        return success(voList);
    }

    /**
     * 获取病历详细信息
     */
    @GetMapping(value = "/detail")
    @ApiOperation("获取病历详细信息")
    public AjaxResult detail(String id) {
        MedicalRecord medicalRecord = medicalRecordService.getById(id);
        return success(getMedicalRecordListVO(medicalRecord));
    }


    /**
     * 根据病历对象构建病历列表视图对象
     *
     * @param medicalRecord 病历对象，用于从数据库中查询相关的病史信息
     * @return MedicalRecordListVO 返回填充了病史信息的病历列表视图对象
     */
    private MedicalRecordListVO getMedicalRecordListVO(MedicalRecord medicalRecord) {
        MedicalRecordListVO vo = new MedicalRecordListVO();
        BeanUtils.copyProperties(medicalRecord, vo);

        // 根据病历ID查询相关的病史信息，并根据类型进行处理
        List<MedicalHistory> histories = medicalHistoryService.list(Wrappers.<MedicalHistory>lambdaQuery()
                .eq(MedicalHistory::getMedicalRecordId, medicalRecord.getId()));
        if (CollectionUtils.isNotEmpty(histories)) {
            // 处理医生记录的病史
            vo.setDoctorAllergyHistory(histories.stream()
                    .filter(l -> MedicalHistoryDiseaseTypeEnum.ALLERGY_HISTORY.getCode().equals(l.getDiseaseType()))
                    .map(MedicalHistory::getDiseaseContent).collect(Collectors.toList()));
            vo.setDoctorFamilyHistory(histories.stream()
                    .filter(l -> MedicalHistoryDiseaseTypeEnum.FAMILY_HISTORY.getCode().equals(l.getDiseaseType()))
                    .map(MedicalHistory::getDiseaseContent).collect(Collectors.toList()));
            vo.setDoctorPastHistory(histories.stream()
                    .filter(l -> MedicalHistoryDiseaseTypeEnum.PAST_HISTORY.getCode().equals(l.getDiseaseType()))
                    .map(MedicalHistory::getDiseaseContent).collect(Collectors.toList()));

            // 处理病人自述的病史
            List<MedicalHistory> patientMedicalHistory = histories.stream()
                    .filter(l -> MedicalHistoryDiseaseSourceEnum.PATIENT.getCode().equals(l.getDiseaseSource())).collect(Collectors.toList());
            vo.setPatientAllergyHistory(patientMedicalHistory.stream()
                    .filter(l -> MedicalHistoryDiseaseTypeEnum.ALLERGY_HISTORY.getCode().equals(l.getDiseaseType()))
                    .map(MedicalHistory::getDiseaseContent).collect(Collectors.toList()));
            vo.setPatientFamilyHistory(patientMedicalHistory.stream()
                    .filter(l -> MedicalHistoryDiseaseTypeEnum.FAMILY_HISTORY.getCode().equals(l.getDiseaseType()))
                    .map(MedicalHistory::getDiseaseContent).collect(Collectors.toList()));
            vo.setPatientPastHistory(patientMedicalHistory.stream()
                    .filter(l -> MedicalHistoryDiseaseTypeEnum.PAST_HISTORY.getCode().equals(l.getDiseaseType()))
                    .map(MedicalHistory::getDiseaseContent).collect(Collectors.toList()));
        }

        vo.setRecordDetailsList(medicalRecordDetailsService.list(Wrappers.<MedicalRecordDetails>lambdaQuery()
                .eq(MedicalRecordDetails::getMedicalRecordId, medicalRecord.getId())));
        return vo;
    }

    /**
     * 新增病历
     */
    @Log(title = "新增病历", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation("新增病历")
    public AjaxResult add(@Valid @RequestBody MedicalRecordSaveParam param) {
        medicalRecordService.addOrEdit(param);
        return success();
    }

    /**
     * 修改病历
     */
    @Log(title = "修改病历", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation("修改病历")
    public AjaxResult edit(@Valid @RequestBody MedicalRecordSaveParam param) {
        if (StringUtils.isEmpty(param.getId())) {
            return error();
        }
        medicalRecordService.addOrEdit(param);
        return success();
    }

    /**
     * 删除病历
     */
    @Log(title = "删除病历", businessType = BusinessType.DELETE)
    @DeleteMapping("/remove")
    @ApiOperation("删除病历")
    public AjaxResult remove(String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        return toAjax(medicalRecordService.removeBatchByIds(idList));
    }

    /**
     * 根据患者ID查询其牙齿治疗状态
     * 该接口通过患者ID从医疗记录中检索患者的牙齿治疗信息，并根据治疗状态进行过滤。
     * 如果指定了治疗状态类型（type参数），则只返回匹配该治疗状态的牙齿信息。
     *
     * @param patientId 患者ID，用于查询患者的医疗记录。
     * @param type      治疗状态类型，可选参数，用于过滤牙齿治疗信息。
     * @return 返回一个包含患者牙齿治疗状态的列表。如果患者没有相关记录，则返回空列表。
     */
    @GetMapping(value = "/teethListByPatientId")
    @ApiOperation("根据患者id查询牙齿治疗状态")
    public AjaxResult teethListByPatientId(@RequestParam(name = "patientId") String patientId,
                                           @RequestParam(name = "type", required = false) Integer type) {
        // 根据患者ID查询所有的医疗记录，并按创建日期降序排序
        List<MedicalRecord> list = medicalRecordService.list(Wrappers.<MedicalRecord>lambdaQuery()
                .eq(MedicalRecord::getPatientId, patientId)
                .orderByDesc(MedicalRecord::getCreateDate));

        // 如果没有查询到医疗记录，直接返回空列表
        if (CollectionUtils.isEmpty(list)) {
            return success(new ArrayList<>());
        }

        List<PatientTeethInfoDto> dtoList = new ArrayList<>();
        for (MedicalRecord medicalRecord : list) {
            PatientTeethInfoDto dto = new PatientTeethInfoDto();

            // 根据治疗状态类型查询对应的医疗记录详情
            List<MedicalRecordDetails> recordDetails = medicalRecordDetailsService.list(Wrappers.<MedicalRecordDetails>lambdaQuery()
                    .eq(Objects.nonNull(type), MedicalRecordDetails::getToothStatus, type)
                    .eq(MedicalRecordDetails::getMedicalRecordId, medicalRecord.getId()));

            // 如果没有找到匹配的医疗记录详情，跳过当前循环
            if (CollectionUtils.isEmpty(recordDetails)) {
                continue;
            }

            // 将医疗记录详情按牙齿位置分组，以便后续处理
            Map<String, List<MedicalRecordDetails>> collect = recordDetails.stream().collect(Collectors.groupingBy(MedicalRecordDetails::getToothPosition));

            for (String s : collect.keySet()) {
                List<MedicalRecordDetails> details = collect.get(s);
                // 从每个分组中选择第一个记录（因为它们按创建日期排序，这意味这是最新地记录）
                Optional<MedicalRecordDetails> first = details.stream().findFirst();

                // 如果找到了最新的记录
                if (first.isPresent()) {
                    MedicalRecordDetails medicalRecordDetails = first.get();

                    // 设置DTO的属性，包括患者ID、牙齿状态、牙齿位置、医疗记录ID等
                    dto.setPatientId(patientId);
                    dto.setToothPositionStatus(medicalRecordDetails.getToothStatus());
                    dto.setToothPosition(medicalRecordDetails.getToothPosition());
                    dto.setMedicalRecordId(medicalRecord.getId());
                    dto.setMedicalRecordDetailsId(medicalRecordDetails.getId());

                    // 根据医疗记录详情中的诊断类型ID，查询并设置诊断类型名称
                    DiagnosisManage manage = diagnosisManageService.getById(medicalRecordDetails.getDiagnosisManageId());
                    if (Objects.nonNull(manage)) {
                        dto.setDiagnosisTypeName(manage.getDiagnosisName());
                    }

                    // 设置医疗记录的创建日期
                    dto.setCreateDate(medicalRecord.getCreateDate());

                    // 将处理好的DTO添加到结果列表中
                    dtoList.add(dto);
                }
            }
        }

        return success(dtoList);
    }


    @GetMapping("/medical-record-list")
    @ApiOperation("就诊记录-查询病历列表")
    public TableDataInfo medicalRecordList(@RequestParam(name = "searchParam", required = false) String searchParam) {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        List<MedicalRecordListDto> list = medicalRecordService.medicalRecordList(searchParam);
        return subList(list, pageNum, pageSize);
    }

    @GetMapping("/checkVisitTypeByToothPosition")
    @ApiOperation("通过牙位验证就诊类型")
    public AjaxResult checkVisitTypeByToothPosition(@RequestParam(name = "toothPosition") String toothPosition,
                                                    @RequestParam(name = "patientId") String patientId) {
        MedicalRecordHistoryDto dto = new MedicalRecordHistoryDto();
        dto.setPatientId(patientId);
        dto.setToothPositionList(Collections.singletonList(toothPosition));
        List<MedicalRecord> list = medicalRecordService.findListByToothPosition(dto);
        return success(Objects.nonNull(list) && list.size() > 0);
    }

    @PostMapping("/findListByToothPosition")
    @ApiOperation("历史病例")
    public AjaxResult findListByToothPosition(@RequestBody MedicalRecordHistoryDto dto) {
        List<MedicalRecord> list = medicalRecordService.findListByToothPosition(dto);
        List<MedicalRecordListVO> voList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(list)) {
            for (MedicalRecord record : list) {
                voList.add(getMedicalRecordListVO(record));
            }
        }
        return success(voList);
    }

    @PostMapping("/findNoteList")
    @ApiOperation("便签列表")
    public AjaxResult findNoteList(@RequestBody MedicalRecordHistoryDto dto) {
        List<MedicalRecordNoteVO> voList = new ArrayList<>();
        MedicalRecordNoteVO vo;
        List<MedicalRecord> recordList = medicalRecordService.findListByToothPosition(dto);
        if (CollectionUtils.isNotEmpty(recordList)) {
            for (MedicalRecord medicalRecord : recordList) {
                vo = new MedicalRecordNoteVO();
                vo.setCreateDate(medicalRecord.getCreateDate());
                vo.setNoteContent(medicalRecord.getNoteContent());
                vo.setDiagnosisContent(medicalRecord.getDiagnosisContent());
                List<MedicalRecordDetails> list = medicalRecordDetailsService.list(Wrappers.<MedicalRecordDetails>lambdaQuery()
                        .eq(MedicalRecordDetails::getMedicalRecordId, medicalRecord.getId()));

                if (CollectionUtils.isNotEmpty(list)) {
                    List<MedicalRecordToothVO> toothList = new ArrayList<>();
                    MedicalRecordToothVO toothVO;
                    for (MedicalRecordDetails medicalRecordDetails : list) {
                        toothVO = new MedicalRecordToothVO();
                        BeanUtils.copyProperties(medicalRecordDetails, toothVO);
                        toothList.add(toothVO);
                    }
                    vo.setToothList(toothList);
                }
                voList.add(vo);
            }
        }

        return success(voList);
    }

    @PostMapping("/getInfoByDiagnosisTypeTemplateId")
    @ApiOperation("通过诊断模板id获取病例数据")
    public AjaxResult getInfoByDiagnosisTypeTemplateId(@RequestBody MedicalRecordParam param) {
        DiagnosisTypeTemplate diagnosisTypeTemplate = diagnosisTypeTemplateService.getById(param.getDiagnosisTypeTemplateId());
        String patientId = param.getPatientId();
        // 封装模板信息
        DiagnosisTypeTemplateDto dto = new DiagnosisTypeTemplateDto();
        dto.setPatientId(patientId);
        dto.setMainDiagnosis(diagnosisTypeTemplate.getDiagnosisManageName());
        dto.setMainDiagnosisId(diagnosisTypeTemplate.getDiagnosisManageId());
        dto.setPatientAllergyHistory(medicalHistoryService.findMedicalHistory(patientId, MedicalHistoryDiseaseTypeEnum.ALLERGY_HISTORY.getCode()));
        dto.setPatientPastHistory(medicalHistoryService.findMedicalHistory(patientId, MedicalHistoryDiseaseTypeEnum.PAST_HISTORY.getCode()));
        dto.setPatientFamilyHistory(medicalHistoryService.findMedicalHistory(patientId, MedicalHistoryDiseaseTypeEnum.FAMILY_HISTORY.getCode()));
        dto.setChiefComplaintOption(JSONObject.parseObject(diagnosisTypeTemplate.getChiefComplaintOption()));
        dto.setPresentIllnessOption(JSONObject.parseObject(diagnosisTypeTemplate.getPresentIllnessOption()));
        dto.setInspectOption(JSONObject.parseObject(diagnosisTypeTemplate.getInspectOption()));
        dto.setTreatmentPlanningOption(JSONObject.parseObject(diagnosisTypeTemplate.getTreatmentPlanningOption()));
        dto.setDisposeOption(JSONObject.parseObject(diagnosisTypeTemplate.getDisposeOption()));
        dto.setNoteOption(JSONObject.parseObject(diagnosisTypeTemplate.getNoteOption()));

        dto.setChiefComplaintContent(JSONObject.parseObject(diagnosisTypeTemplate.getChiefComplaintOption()).getString("text"));
        dto.setPresentIllnessContent(JSONObject.parseObject(diagnosisTypeTemplate.getPresentIllnessOption()).getString("text"));
        dto.setInspectContent(JSONObject.parseObject(diagnosisTypeTemplate.getInspectOption()).getString("text"));
        dto.setTreatmentPlanningContent(JSONObject.parseObject(diagnosisTypeTemplate.getTreatmentPlanningOption()).getString("text"));
        dto.setDisposeContent(JSONObject.parseObject(diagnosisTypeTemplate.getDisposeOption()).getString("text"));
        dto.setNoteContent(JSONObject.parseObject(diagnosisTypeTemplate.getNoteOption()).getString("text"));

        dto.setId(diagnosisTypeTemplate.getId());

        List<String> otherDiagnosisTypeTemplateIdList = param.getOtherDiagnosisTypeTemplateIdList();
        if (CollectionUtils.isNotEmpty(otherDiagnosisTypeTemplateIdList)) {
            List<DiagnosisTypeTemplate> list = diagnosisTypeTemplateService.listByIds(otherDiagnosisTypeTemplateIdList);
            dto.setOtherDiagnosis(list.stream().map(DiagnosisTypeTemplate::getDiagnosisManageName).collect(Collectors.toList()));
        }

        return success(dto);
    }

    //subList手动分页，page为第几页，rows为每页个数
    public static TableDataInfo subList(List<MedicalRecordListDto> list, int page, int rows) {
        List<MedicalRecordListDto> listSort = new ArrayList<>();
        int size = list.size();
        int pageStart = page == 1 ? 0 : (page - 1) * rows;//截取的开始位置
        int pageEnd = Math.min(size, page * rows);//截取的结束位置
        if (size > pageStart) {
            listSort = list.subList(pageStart, pageEnd);
        }

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(listSort);
        rspData.setTotal(list.size());
        return rspData;
    }

}
