package com.cirle.scientific.service.impl;/*
 *24901
 *2022/12/26
 *16:15
 */

import cn.hutool.core.collection.CollectionUtil;
import com.cirle.scientific.dao.QkjLungReportAppDao;
import com.cirle.scientific.dao.QkjMemberAppDao;
import com.cirle.scientific.dto.lungreport.LungReportAddReq;
import com.cirle.scientific.dto.lungreport.LungReportFindRes;
import com.cirle.scientific.dto.lungreport.LungReportSearchResDTO;
import com.cirle.scientific.po.QkjLungReportApp;
import com.cirle.scientific.po.QkjMemberApp;
import com.cirle.scientific.po.QkjPatientApp;
import com.cirle.scientific.pojo.SexEnum;
import com.cirle.scientific.service.PatientAppService;
import com.cirle.scientific.service.QkjLungReportAppService;
import com.cirle.scientific.service.QuestionnaireService;
import com.cirle.scientific.utils.CopyUtil;
import com.cirle.scientific.utils.DateFormater;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 24901
 */
@Service
@Slf4j
public class QkjLungReportAppServiceImpl implements QkjLungReportAppService {

    private static final String ACCOMPLISH = "已完成";

    private static final String NOTACCOMPLISH = "未完成";

    private QkjLungReportAppDao qkjLungReportAppDao;

    private QuestionnaireService questionnaireService;

    private QkjMemberAppDao qkjMemberAppDao;

    private PatientAppService patientAppService;

    @Autowired
    public void setPatientAppService(PatientAppService patientAppService) {
        this.patientAppService = patientAppService;
    }

    @Autowired
    public void setQkjMemberAppDao(QkjMemberAppDao qkjMemberAppDao) {
        this.qkjMemberAppDao = qkjMemberAppDao;
    }

    @Autowired
    public void setQuestionnaireService(QuestionnaireService questionnaireService) {
        this.questionnaireService = questionnaireService;
    }

    @Autowired
    public void setQkjLungReportAppDao(QkjLungReportAppDao qkjLungReportAppDao) {
        this.qkjLungReportAppDao = qkjLungReportAppDao;
    }


    @Override
    public int addLungReport(LungReportAddReq req) {
        try {
            String[] picture = req.getPicture();
            SexEnum sexEnum = SexEnum.valueOf(req.getSex());
            //讲图片用逗号隔开保存
            StringBuilder pictures = null;
            if(!ObjectUtils.isEmpty(picture)){
                for (int i = 0; i < picture.length; i++) {
                    String s = picture[i];
                    if(picture.length == 1){
                        pictures = new StringBuilder(s);
                        continue;
                    }
                    if(i == 0){
                        pictures = new StringBuilder(s + ",");
                        continue;
                    }
                    //最后一个不加逗号
                    if(picture.length-1 == i){
                        pictures.append(s);
                    }else{
                        pictures.append(s).append(",");
                    }
                }
            }
            QkjLungReportApp qkjLungReportApp = CopyUtil.copy(req, QkjLungReportApp.class);
            assert pictures != null;
            qkjLungReportApp.setPicture(pictures.toString());
            qkjLungReportApp.setStatus(0);
            qkjLungReportApp.setSex(sexEnum.getType());
            if(req.getId() == null){
                qkjLungReportApp.setCreateTime(new Date());
            }else{
                QkjLungReportApp lungReportApp = qkjLungReportAppDao.findById(req.getId()).orElseGet(QkjLungReportApp::new);
                qkjLungReportApp.setCreateTime(lungReportApp.getCreateTime());
                qkjLungReportApp.setUpdateTime(new Date());
            }
            Long id = qkjLungReportAppDao.save(qkjLungReportApp).getId();
            return id.intValue();
        } catch (Exception e) {
            e.printStackTrace();
            log.info("/app/LungReportApp/addLungReport方法出错 e->{e}", e);
            return 500;
        }
    }

    @Override
    public LungReportFindRes findLungReport(Long id) {
        QkjLungReportApp qkjLungReportApp = qkjLungReportAppDao.findAllByIdAndStatus(id);
        SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        LungReportFindRes lungReportFindRes = null;
        try {
            if(!ObjectUtils.isEmpty(qkjLungReportApp)){
                String picture = qkjLungReportApp.getPicture();
                String[] pictures = picture.split(",");
                lungReportFindRes = CopyUtil.copy(qkjLungReportApp, LungReportFindRes.class);
                if(null != lungReportFindRes.getMemCard()){
                    String memNickname = qkjMemberAppDao.findByMemCard(lungReportFindRes.getMemCard()).getMemNickname();
                    lungReportFindRes.setDoctorName(memNickname);
                }
                lungReportFindRes.setPicture(pictures);
                if(null != qkjLungReportApp.getCreateTime()){
                    String format = bartDateFormat.format(qkjLungReportApp.getCreateTime());
                    lungReportFindRes.setCreateTime(format);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("接口:/app/LungReportApp/findLungReport报错 e->{e}", e);
        }
        return lungReportFindRes;
    }

    @Override
    public int delLungReport(Long id) {
        try {
            QkjLungReportApp qkjLungReportApp = qkjLungReportAppDao.findAllByIdAndStatus(id);
            if(null != qkjLungReportApp){
                qkjLungReportApp.setStatus(1);
                qkjLungReportAppDao.save(qkjLungReportApp);
            }
            return 200;
        } catch (Exception e) {
            e.printStackTrace();
            log.info("/app/LungReportApp/delLungReport方法出错 e->{e}", e);
            return 500;
        }

    }

    @Override
    public List<QkjLungReportApp> findByMemCard(String memCard) {
        return qkjLungReportAppDao.findAllByMemCardAndStatus(memCard);
    }

    @Override
    public Map<String , Object> findLungQuantity(String memCard) {
        Map<String , Object> data = new HashMap<>();
        try {
            String firstDay = DateFormater.thisMonthFirstDay();
            String lastDay = DateFormater.thisMonthLastDay();
            //查询出当前医生名下当月所有的患者信息
            List<QkjPatientApp> doctorQuestions = questionnaireService.findDoctorQuestions(memCard);
            //过滤条件分数
            List<QkjPatientApp> patientSize = doctorQuestions.stream().filter(a -> null != a.getOneQuestionnaireScore() && a.getOneQuestionnaireScore() >= 16 || null != a.getTowQuestionnaireScore() && a.getTowQuestionnaireScore() >= 5).collect(Collectors.toList());
            if(CollectionUtil.isNotEmpty(patientSize)){
                data.put("patientSize",patientSize.size());
            }else{
                data.put("patientSize",0);
            }
            double reportRate = patientSize.size() * 0.95;
            int lungSize = qkjLungReportAppDao.findAllByMemCardAndStatusAAndCreateTime(memCard, firstDay, lastDay);
            data.put("lungSize",lungSize);
            data.put("reportRate",Math.round(reportRate));
            if(lungSize >= reportRate && doctorQuestions.size() >= 25){
                data.put("isPass",1);
            }else{
                data.put("isPass",0);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("方法 findLungQuantity 报错e->{e}", e);
        }
        return data;
    }

    @Override
    public Map<String , Object> findLungCount(String memCard) {
        Map<String , Object> data = new HashMap<>();
        try {
            QkjMemberApp byMemCard = qkjMemberAppDao.findByMemCard(memCard);
            if(null != byMemCard){
                data.put("name",byMemCard.getMemNickname());
            }else{
                data.put("name",null);
            }
            String firstDay = DateFormater.thisMonthFirstDay();
            String lastDay = DateFormater.thisMonthLastDay();
            //查询出当前医生名下当月所有的患者信息
            List<QkjPatientApp> doctorQuestions = questionnaireService.findDoctorQuestions(memCard);
            data.put("patientSize", doctorQuestions.size());
            int lungSize = qkjLungReportAppDao.findAllByMemCardAndStatusAAndCreateTime(memCard, firstDay, lastDay);
            data.put("lungSize", lungSize);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("接口/app/LungReportApp/findLungCount报错 e->{e}", e);
        }
        return data;
    }

    @Override
    public List<LungReportSearchResDTO> findQuestionAndLung(String memCard, String patientName) {
        List<LungReportSearchResDTO> data = new ArrayList<>();
        LungReportSearchResDTO lungReportSearchResDTO = new LungReportSearchResDTO();
        String memNickname = qkjMemberAppDao.findByMemCard(memCard).getMemNickname();
        try {
            //根具姓名获取当下医生中所有患者信息
            QkjPatientApp qkjPatientApps = patientAppService.findAllByMemCardAndName(memCard, patientName);
            //根具姓名获取当下医生中所有患者肺功能信息
            QkjLungReportApp qkjLungReportApps = qkjLungReportAppDao.findAllByMemCardAndUserNameAndStatus(memCard, patientName);
            if(null == qkjPatientApps  && null == qkjLungReportApps){
                return null;
            }
            if(null != memNickname){
                lungReportSearchResDTO.setQuestionDoctorName(memNickname);
            }
            lungReportSearchResDTO.setPatientName(patientName);
            if(null != qkjPatientApps && null != qkjPatientApps.getIsAccomplishQuestion()  && qkjPatientApps.getIsAccomplishQuestion() == 1){
                lungReportSearchResDTO.setQuestionAccomplish(ACCOMPLISH);
            }else{
                lungReportSearchResDTO.setQuestionAccomplish(NOTACCOMPLISH);
            }
            if(null != qkjLungReportApps){
                lungReportSearchResDTO.setLungId(qkjLungReportApps.getId().intValue());
                if(null != qkjLungReportApps.getPicture() && qkjLungReportApps.getPicture().split(",").length != 0){
                    lungReportSearchResDTO.setLungAccomplish(ACCOMPLISH);
                }else{
                    lungReportSearchResDTO.setLungAccomplish(NOTACCOMPLISH);
                }
                if(null != memNickname){
                    lungReportSearchResDTO.setLungDoctorName(memNickname);
                }
            }
            data.add(lungReportSearchResDTO);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("接口/app/LungReportApp/findQuestionAndLung 报错 e->{e}", e);
        }
        return data;
    }
}
