package com.rf.psychological.scale.resultBusiness.scaleResult;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rf.psychological.dao.dto.scale.NewResultDto;
import com.rf.psychological.dao.model.AnswerEntity;
import com.rf.psychological.dao.model.DimensionEntity;
import com.rf.psychological.scale.dao.model.DimensionOrgEntity;
import com.rf.psychological.scale.dao.model.ScaleMarksEntity;
import com.rf.psychological.scale.dao.model.WarnEntity;
import com.rf.psychological.scale.service.DimensionOrgService;
import com.rf.psychological.utils.Constant;
import org.springframework.beans.BeanUtils;

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

import static com.rf.psychological.scale.resultBusiness.scaleResult.SCSQScale.createWarnEntry;

/**
 * @author zsy
 * @description:症状自评量表 flag=20210617140713
 * @date 2021/7/20 15:55
 */
public class SCL90Scale extends BaseScale {

    public SCL90Scale(JSONArray jsonArray, JSONObject resultJson) {
        super(jsonArray, resultJson);
    }

    public JSONObject scaleCalculate() throws Exception {

        //总分
        double score = 0;
        //总均分
        double GPA = 0;
        //阳性项目数
        int positive = 0;
        //阳性项目总分
        int positiveScore = 0;

        Map<String, String> resultMap0 = new LinkedHashMap<>();
        //老版本数据格式
        Map<String, Object> newResult = new LinkedHashMap<>();
        List<Map<String, String>> resultMapList = new ArrayList<>();


        //获取答案列表
        List<AnswerEntity> answerEntities = (List<AnswerEntity>) resultJson.get("answerEntities");
        //获取评分规则列表
        List<ScaleMarksEntity> scaleMarksEntities = (List<ScaleMarksEntity>) resultJson.get("scaleMarksEntities");
        //获取维度信息列表
        List<DimensionEntity> dimensionEntities = (List<DimensionEntity>) resultJson.get("dimensionEntities");
        //计算每个维度得分dimensionEntities
        double[] dimensionScore = new double[dimensionEntities.size()];
        Map<String,Double> dimensionScoreMap = new HashMap<>();
        //jsonArray:用户自己选择的题目选项
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject1 = jsonArray.getJSONObject(i);
            for (int y = 0; y < dimensionEntities.size(); y++) {
                //获取维度信息
                DimensionEntity dimensionEntity = dimensionEntities.get(y);
                //获取该维度下有哪些选项
                String questionNos = dimensionEntity.getQuestionNo();
                //得到选择题号
                String[] questionNo = questionNos.split("；");
                //计算每道题的得分
                for (String question : questionNo) {
                    if (question.equals(jsonObject1.getString("questionNo"))) {
                        //获取所有答案中本道题目的答案list数组
                        List<AnswerEntity> nowQuestionAnswerList = answerEntities.stream().filter(answerEntity -> answerEntity.getQuestionNo().equals(question)).collect(Collectors.toList());
                        //本题目的正确答案与自己的选项进行对比，正确的话相应分数进行相加
                        for (AnswerEntity answerEntity : nowQuestionAnswerList) {
                            if (answerEntity.getName().equals(jsonObject1.getString("checkItems"))) {
                                dimensionScore[y] += Double.parseDouble(answerEntity.getScore());
                                dimensionScoreMap.put(dimensionEntity.getId(),dimensionScoreMap.get(dimensionEntity.getId())==null?Double.parseDouble(answerEntity.getScore()):(dimensionScoreMap.get(dimensionEntity.getId()) +Double.parseDouble(answerEntity.getScore())));
                                //如果用户选择的当前题目的的分数大于2分，即为阳性项目分，并进行处理
                                if (Integer.parseInt(answerEntity.getScore()) >= 2) {
                                    positive += 1;
                                    positiveScore += Integer.parseInt(answerEntity.getScore());
                                }
                                //计算总分
                                score += Integer.parseInt(answerEntity.getScore());
                                break;
                            }
                        }
                    }
                }
            }
        }
        if(dimensionScoreMap.size()>0){
            resultJson.put("dimensionScoreMap",dimensionScoreMap);
        }
        //将量表总维度根据维度名称进行分组
        Map<String, List<ScaleMarksEntity>> scaleMarksMap = scaleMarksEntities.stream().collect(Collectors.groupingBy(ScaleMarksEntity::getName));
        //返回值以及存数据库格式
        List<NewResultDto> newResultDtos = new ArrayList<>();

        resultMap0.put("总分", String.valueOf(score));
        resultJson.put("总分", String.valueOf(score));
        DecimalFormat df = new DecimalFormat("######0.00");
        GPA = Double.parseDouble(df.format(score / 90));
        resultMap0.put("总均分", String.valueOf(GPA));
        resultJson.put("总均分", String.valueOf(GPA));

        List<ScaleMarksEntity> totalScore = scaleMarksMap.get("总分");
        ScaleMarksEntity tempTotalScore = totalScore.get(0);
        newResultDtos.add(new NewResultDto("总分", String.valueOf(score), tempTotalScore.getSymptom(), tempTotalScore.getImprovementSuggestions(),
                tempTotalScore.getFlag(), tempTotalScore.getReference(), tempTotalScore.getNameExplain(), tempTotalScore.getSuggestion(), tempTotalScore.getIsTotalScoreExplain()));

        List<ScaleMarksEntity> gpaScale = scaleMarksMap.get("总均分");
        for (ScaleMarksEntity scaleMarksEntity : gpaScale) {
            if (GPA <= Double.parseDouble(df.format(Double.parseDouble(scaleMarksEntity.getScoreEnd()))) && GPA >= Double.parseDouble(df.format(Double.parseDouble(scaleMarksEntity.getScoreStart())))) {
                resultMap0.put("总均分常模参考值", scaleMarksEntity.getReference());
                resultMap0.put("总均分解释", scaleMarksEntity.getSymptom());
                resultJson.put("总均分解释", scaleMarksEntity.getSymptom());
                resultMap0.put("总均分解读", scaleMarksEntity.getNameExplain());
                resultMap0.put("总均分说明", scaleMarksEntity.getImprovementSuggestions());
                resultMap0.put("总均分建议", scaleMarksEntity.getSuggestion());

                NewResultDto newResultDto = new NewResultDto();
                BeanUtils.copyProperties(scaleMarksEntity, newResultDto);
                newResultDto.setScore(String.valueOf(GPA));
                newResultDtos.add(newResultDto);
            }
        }

        resultMap0.put("阳性项目数", String.valueOf(positive));
        resultJson.put("阳性项目数", String.valueOf(positive));
        List<ScaleMarksEntity> tempPositive = scaleMarksMap.get("阳性项目数");
        ScaleMarksEntity scaleMarksEntity1 = tempPositive.get(0);
        NewResultDto newResultDto = new NewResultDto();
        BeanUtils.copyProperties(scaleMarksEntity1, newResultDto);
        newResultDto.setScore(String.valueOf(positive));
        newResultDtos.add(newResultDto);

        resultMap0.put("阴性项目数", String.valueOf(90 - positive));
        resultJson.put("阴性项目数", String.valueOf(90 - positive));
        List<ScaleMarksEntity> tempPositive1 = scaleMarksMap.get("阴性项目数");
        NewResultDto newResultDto2 = new NewResultDto();
        BeanUtils.copyProperties(tempPositive1.get(0), newResultDto2);
        newResultDto2.setScore(String.valueOf(90 - positive));
        newResultDtos.add(newResultDto2);

        NewResultDto newResultDto3 = new NewResultDto();
        if (positive == 0) {
            resultMap0.put("阳性症状均分", "0");
            resultJson.put("阳性症状均分", "0");
            newResultDto3.setScore("0");
        } else {
            resultMap0.put("阳性症状均分", String.valueOf(Double.parseDouble(df.format(positiveScore / positive))));
            resultJson.put("阳性症状均分", String.valueOf(Double.parseDouble(df.format(positiveScore / positive))));
            newResultDto3.setScore(String.valueOf(Double.parseDouble(df.format(positiveScore / positive))));
        }
        List<ScaleMarksEntity> tempPositive2 = scaleMarksMap.get("阳性项目均分");
        BeanUtils.copyProperties(tempPositive2.get(0), newResultDto3);
        newResultDtos.add(newResultDto3);

        JSONObject iconInfo = new JSONObject();
        //雷达图需要的维度以及最大值
        List<Map<String, Object>> indicator = new LinkedList<>();
        //雷达图所需要的常模参考值
        LinkedList<String> reference = new LinkedList<>();
        Map<String ,Double> dimensionOrg =  new HashMap<>();
        //雷达图需要的分数
        LinkedList<String> scoreList = new LinkedList<>();
        for (int y = 0; y < dimensionEntities.size(); y++) {
            Map<String, Object> indicatorMap = new HashMap<>();
            DimensionEntity dimensionEntity = dimensionEntities.get(y);
            NewResultDto newResultDto1 = new NewResultDto();
            String questionNos = dimensionEntity.getQuestionNo();
            String[] questionNo = questionNos.split("；");
            double resultScore = Double.parseDouble(df.format(dimensionScore[y] / questionNo.length));
            dimensionOrg.put(dimensionEntity.getId(),resultScore);
            //存放该维度总分
            resultMap0.put(dimensionEntity.getName()+"得分", String.valueOf(resultScore));
            resultJson.put(dimensionEntity.getName()+"得分", String.valueOf(resultScore));
            newResultDto1.setScore(String.valueOf(resultScore));
            newResultDtos.add(newResultDto1);
            //获取当前维度的评分规则
            List<ScaleMarksEntity> scaleMarksEntities1 = scaleMarksMap.get(dimensionEntity.getName());
            //循环遍历判断得分在哪个区间
            for (ScaleMarksEntity scaleMarksEntity : scaleMarksEntities1) {
                if (resultScore <= Double.parseDouble(df.format(Double.parseDouble(scaleMarksEntity.getScoreEnd()))) && resultScore >= Double.parseDouble(df.format(Double.parseDouble(scaleMarksEntity.getScoreStart())))) {
                    putDimResult(resultMap0, resultJson, dimensionEntity, newResultDto1, scaleMarksEntity);
                    //需要进行图表展示的维度放入map
                    if ("1".equals(dimensionEntity.getIsIconFlag())) {
                        indicatorMap.put("text", dimensionEntity.getName());
                        indicatorMap.put("max", scaleMarksEntity.getScoreEnd());
                        indicator.add(indicatorMap);
                        if ("无".equals(scaleMarksEntity.getReference()) || "无".equals(scaleMarksEntity.getStandardDeviation())) {
                            //常模参考值设为0
                            reference.add("0");
                        } else {
                            reference.add(scaleMarksEntity.getReference());
                        }
                        scoreList.add(String.valueOf(resultScore));
                    }
                }
            }
        }
        //需要图表展示的
        iconInfo.put("indicator", indicator);
        iconInfo.put("reference", reference);
        iconInfo.put("scoreList", scoreList);
        newResult.put("iconInfo", iconInfo);
        newResult.put("result", newResultDtos);
        resultMapList.add(resultMap0);

        JSONObject returnJson = new JSONObject(true);
        returnJson.put("resultMapList", resultMapList);
        returnJson.put("scaleName", Constant.SHEET_NAME_SCL_90);
        returnJson.put("resultJson", resultJson);
        returnJson.put("newResultJson", newResult);
        DimensionOrgService dimensionOrgService = (DimensionOrgService) resultJson.get("dimensionOrgService");
        String institutionNo = resultJson.getString("institutionNo");
        List<WarnEntity> warnEntityList = new ArrayList<>();
        String userId = resultJson.getString("userId");
       /* //  预警信息
        dimensionOrg.forEach((key, value) -> {
            //预警维度
            DimensionOrgEntity byInstitutionNoAndDimensionId = dimensionOrgService.findByInstitutionNoAndDimensionId(institutionNo, key);
            if (byInstitutionNoAndDimensionId != null) {
                double currentScore = dimensionOrg.get(key);// 得分
                switch (byInstitutionNoAndDimensionId.getLogic()) {
                    case "lt":
                        if (currentScore < Double.parseDouble(byInstitutionNoAndDimensionId.getThreshold())) {
                            //添加预警信息
                            warnEntityList.add(createWarnEntry(Constant.QUEST_FLAG_SCL_90, institutionNo, userId, key, currentScore));
                        }
                        break;
                    case "le":
                        if (currentScore <= Double.parseDouble(byInstitutionNoAndDimensionId.getThreshold())) {
                            //添加预警信息
                            warnEntityList.add(createWarnEntry(Constant.QUEST_FLAG_SCL_90, institutionNo, userId, key, currentScore));
                        }
                        break;
                    case "eq":
                        if (currentScore == Double.parseDouble(byInstitutionNoAndDimensionId.getThreshold())) {
                            //添加预警信息
                            warnEntityList.add(createWarnEntry(Constant.QUEST_FLAG_SCL_90, institutionNo, userId, key, currentScore));
                        }
                        break;
                    case "ne":
                        if (currentScore != Double.parseDouble(byInstitutionNoAndDimensionId.getThreshold())) {
                            //添加预警信息
                            warnEntityList.add(createWarnEntry(Constant.QUEST_FLAG_SCL_90, institutionNo, userId, key, currentScore));
                        }
                        break;
                    case "ge":
                        if (currentScore >= Double.parseDouble(byInstitutionNoAndDimensionId.getThreshold())) {
                            //添加预警信息
                            warnEntityList.add(createWarnEntry(Constant.QUEST_FLAG_SCL_90, institutionNo, userId, key, currentScore));
                        }
                        break;
                    case "gt":
                        if (currentScore > Double.parseDouble(byInstitutionNoAndDimensionId.getThreshold())) {
                            //添加预警信息
                            warnEntityList.add(createWarnEntry(Constant.QUEST_FLAG_SCL_90, institutionNo, userId, key, currentScore));
                        }
                        break;
                }

            }
        });*/
        resultJson.put("warnEntityList",warnEntityList);
        return returnJson;
    }

    private static void putDimResult(Map<String, String> resultMap0, JSONObject oldResult, DimensionEntity dimensionEntity, NewResultDto newResultDto1, ScaleMarksEntity scaleMarksEntity) {
        resultMap0.put(dimensionEntity.getName() + "常模参考值", scaleMarksEntity.getReference());
        resultMap0.put(dimensionEntity.getName() + "解释", scaleMarksEntity.getSymptom());
        oldResult.put(dimensionEntity.getName() + "解释", scaleMarksEntity.getSymptom());
        resultMap0.put(dimensionEntity.getName() + "解读", scaleMarksEntity.getNameExplain());
        resultMap0.put(dimensionEntity.getName() + "说明", scaleMarksEntity.getImprovementSuggestions());
        resultMap0.put(dimensionEntity.getName() + "建议", scaleMarksEntity.getSuggestion());
        BeanUtils.copyProperties(scaleMarksEntity, newResultDto1);
    }
}
