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.ScaleMarksEntity;
import com.rf.psychological.scale.scaleresult.ScaleConstant;
import com.rf.psychological.utils.Constant;
import org.springframework.beans.BeanUtils;
import org.springframework.lang.Nullable;

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

import static com.rf.psychological.scale.resultBusiness.scaleResult.NEWCOMMONScale.commonComputeDimensionScore;

/**
 * @author ZSY
 * @description:明尼苏达多项人格量表完整版
 * @date 2022/4/22 15:55
 */
public class MMPI566Scale extends BaseScale {

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

    public JSONObject scaleCalculate() throws Exception {

        //总分
        double score = 0;
        DecimalFormat df = new DecimalFormat("######0.00");

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

        //获取答案列表
        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 (AnswerEntity answerEntity : answerEntities) {
                if (answerEntity.getQuestionNo().equals(jsonObject1.getString("questionNo"))) {
                    if (answerEntity.getName().replaceAll("\\s", "").equals(jsonObject1.getString("checkItems").replaceAll("\\s", ""))) {
                        score += Double.parseDouble(answerEntity.getScore());
                        break;
                    }
                }
            }
            //计算维度分数
            for (int y = 0; y < dimensionEntities.size(); y++) {
                //获取维度信息
                DimensionEntity dimensionEntity = dimensionEntities.get(y);
                //获取该维度下有哪些选项
                String questionNos = dimensionEntity.getQuestionNo();
                //删除空白字符后得到进行划分得到选择题号
                String[] questionNo = questionNos.replaceAll("\\s", "").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().replaceAll("\\s", "").equals(jsonObject1.getString("checkItems").replaceAll("\\s", ""))) {
                                dimensionScoreMap.put(dimensionEntity.getId(),dimensionScoreMap.get(dimensionEntity.getId())==null?Double.parseDouble(answerEntity.getScore()):(dimensionScoreMap.get(dimensionEntity.getId()) +Double.parseDouble(answerEntity.getScore())));
                                dimensionScore[y] += Double.parseDouble(answerEntity.getScore());
                                break;
                            }
                        }
                    }
                }
            }
            resultJson.put("dimensionScoreMap",dimensionScoreMap);
        }

        dimensionScore[1] = Double.parseDouble(df.format(50+10*(dimensionScore[1]-11.93)/5.12));
        dimensionScore[2] = Double.parseDouble(df.format(50+10*(dimensionScore[2]-12.31)/4.55));
        dimensionScore[3] = Double.parseDouble(df.format(50+10*(dimensionScore[3]-14.65)/4.93));
        dimensionScore[4] = Double.parseDouble(df.format(50+10*(dimensionScore[4]-26.32)/5.40));
        dimensionScore[5] = Double.parseDouble(df.format(50+10*(dimensionScore[5]-20.68)/5.33));
        dimensionScore[6] = Double.parseDouble(df.format(50+10*(dimensionScore[6]-22.62)/4.78));
        dimensionScore[7] = Double.parseDouble(df.format(50+10*(dimensionScore[7]-27.07)/4.17));
        dimensionScore[8] = Double.parseDouble(df.format(50+10*(dimensionScore[8]-12.2)/4.11));
        dimensionScore[9] = Double.parseDouble(df.format(50+10*(dimensionScore[9]-29.69)/5.58));
        dimensionScore[10] = Double.parseDouble(df.format(50+10*(dimensionScore[10]-33.92)/7.6));
        dimensionScore[11] = Double.parseDouble(df.format(50+10*(dimensionScore[11]-20.11)/5.6));
        dimensionScore[12] = Double.parseDouble(df.format(50+10*(dimensionScore[12]-33.37)/6.99));
        dimensionScoreMap.put(dimensionEntities.get(1).getId(),dimensionScore[1] );
        dimensionScoreMap.put(dimensionEntities.get(2).getId(),dimensionScore[2] );
        dimensionScoreMap.put(dimensionEntities.get(3).getId(),dimensionScore[3] );
        dimensionScoreMap.put(dimensionEntities.get(4).getId(),dimensionScore[4] );
        dimensionScoreMap.put(dimensionEntities.get(5).getId(),dimensionScore[5] );
        dimensionScoreMap.put(dimensionEntities.get(6).getId(),dimensionScore[6] );
        dimensionScoreMap.put(dimensionEntities.get(7).getId(),dimensionScore[7] );
        dimensionScoreMap.put(dimensionEntities.get(8).getId(),dimensionScore[8] );
        dimensionScoreMap.put(dimensionEntities.get(9).getId(),dimensionScore[9] );
        dimensionScoreMap.put(dimensionEntities.get(10).getId(),dimensionScore[10]);
        dimensionScoreMap.put(dimensionEntities.get(11).getId(),dimensionScore[11]);
        dimensionScoreMap.put(dimensionEntities.get(12).getId(),dimensionScore[12]);
        resultJson.put("dimensionScoreMap",dimensionScoreMap);

        //将量表总维度根据维度名称进行分组
        Map<String, List<ScaleMarksEntity>> scaleMarksMap = scaleMarksEntities.stream().collect(Collectors.groupingBy(ScaleMarksEntity::getName));
        //返回值以及存数据库格式
        List<NewResultDto> newResultDtos = new ArrayList<>();
        resultMap0.put("总分", df.format(score));
        resultJson.put("总分", df.format(score));
        BigDecimal scoreDecimal = new BigDecimal(df.format(score));
        //如果没有总分这一栏，需要手动赋值返回
        List<ScaleMarksEntity> totalScore = scaleMarksMap.get("总分");
        List<ScaleMarksEntity> totalScores = scaleMarksMap.get("无");
        if (totalScore == null) {
            if (totalScores == null){
                newResultDtos.add(new NewResultDto("总分", df.format(score), "无", "无",
                        "无", "无", "无", "无", "是"));
            }else {
                for (ScaleMarksEntity tempTotalScore : totalScores) {
                    BigDecimal scoreStart = new BigDecimal(tempTotalScore.getScoreStart());
                    BigDecimal scoreEnd = new BigDecimal(tempTotalScore.getScoreEnd());
                    if (scoreDecimal.compareTo(scoreEnd) <= 0 && scoreDecimal.compareTo(scoreStart) >= 0) {
                        newResultDtos.add(new NewResultDto("总分", df.format(score), tempTotalScore.getSymptom(), tempTotalScore.getImprovementSuggestions(),
                                tempTotalScore.getFlag(), tempTotalScore.getReference(), tempTotalScore.getNameExplain(), tempTotalScore.getSuggestion(), tempTotalScore.getIsTotalScoreExplain()));
                        resultMap0.put("总分解释", tempTotalScore.getSymptom());
                        resultMap0.put("总分说明", tempTotalScore.getImprovementSuggestions());
                        resultMap0.put("总分解读", tempTotalScore.getNameExplain());
                        resultMap0.put("总分建议", tempTotalScore.getSuggestion());
                        resultJson.put("总分解释", tempTotalScore.getSymptom());
                        resultJson.put("总分说明", tempTotalScore.getImprovementSuggestions());
                        resultJson.put("总分解读", tempTotalScore.getNameExplain());
                        resultJson.put("总分建议", tempTotalScore.getSuggestion());
                    }
                }
            }
        } else {
            for (ScaleMarksEntity tempTotalScore : totalScore) {
                BigDecimal scoreStart = new BigDecimal(tempTotalScore.getScoreStart());
                BigDecimal scoreEnd = new BigDecimal(tempTotalScore.getScoreEnd());
                if (scoreDecimal.compareTo(scoreEnd) <= 0 && scoreDecimal.compareTo(scoreStart) >= 0) {
                    newResultDtos.add(new NewResultDto("总分", df.format(score), tempTotalScore.getSymptom(), tempTotalScore.getImprovementSuggestions(),
                            tempTotalScore.getFlag(), tempTotalScore.getReference(), tempTotalScore.getNameExplain(), tempTotalScore.getSuggestion(), tempTotalScore.getIsTotalScoreExplain()));
                    resultMap0.put("总分解释", tempTotalScore.getSymptom());
                    resultMap0.put("总分说明", tempTotalScore.getImprovementSuggestions());
                    resultMap0.put("总分解读", tempTotalScore.getNameExplain());
                    resultMap0.put("总分建议", tempTotalScore.getSuggestion());
                    resultJson.put("总分解释", tempTotalScore.getSymptom());
                    resultJson.put("总分说明", tempTotalScore.getImprovementSuggestions());
                    resultJson.put("总分解读", tempTotalScore.getNameExplain());
                    resultJson.put("总分建议", tempTotalScore.getSuggestion());
                }
            }
        }


        JSONObject iconInfo = new JSONObject();
        //雷达图需要的维度以及最大值
        List<Map<String, Object>> indicator = new LinkedList<>();
        //雷达图所需要的常模参考值
        LinkedList<String> reference = new LinkedList<>();
        //雷达图需要的分数
        LinkedList<String> scoreList = new LinkedList<>();
        //计算维度所在评分区间
        commonComputeDimensionScore(df, resultMap0, resultJson, dimensionEntities, dimensionScore, scaleMarksMap, newResultDtos, indicator, reference, scoreList);
        //需要图表展示的
        iconInfo.put("indicator", indicator);
        //判断是否有常模参考值，即reference的内容如果全为0，则不进行返回
        if (!reference.stream().allMatch("0"::equals)) {
            iconInfo.put("reference", reference);
        }
        iconInfo.put("scoreList", scoreList);
        if (indicator.size() == 0 && reference.size() == 0) {
            newResult.put("iconInfo", "");
        } else {
            newResult.put("iconInfo", iconInfo);
        }
        newResult.put("result", newResultDtos);
        resultMapList.add(resultMap0);


        JSONObject returnJson = new JSONObject(true);
        returnJson.put("resultMapList", resultMapList);
        returnJson.put("resultJson", resultJson);
        returnJson.put(ScaleConstant.ResultEnum.RESULT_NEW_FIELD.getKeyword(), newResult);

        return returnJson;
    }

}
