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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rf.psychological.dao.model.AnswerEntity;
import com.rf.psychological.scale.dao.model.ScaleMarksEntity;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zsy
 * @description:JSON格式量表通用算法
 * @date 2021/7/20 15:55
 */
public class JSONScale extends BaseScale{

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

    public  JSONObject scaleCalculate() throws Exception {
        //总分
        int score = 0;

        //获取答案列表
        List<AnswerEntity> answerEntities = (List<AnswerEntity>) resultJson.get("answerEntities");
        //获取评分规则列表
        List<ScaleMarksEntity> scaleMarksEntities = (List<ScaleMarksEntity>) resultJson.get("scaleMarksEntities");

        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject1 = jsonArray.getJSONObject(i);
            for (AnswerEntity answerEntity:answerEntities){
                if (answerEntity.getQuestionNo().equals(String.valueOf(i+1))){
                    if (answerEntity.getName().equals(jsonObject1.getString("checkItems"))){
                        score += Integer.valueOf(answerEntity.getScore());
                    }
                }
            }
        }
        Map<String, String> resultMap0 = new LinkedHashMap<>();
        resultMap0.put("总分", String.valueOf(score));
        resultJson.put("总分", String.valueOf(score));
        if (scaleMarksEntities.size() > 0){
            for (ScaleMarksEntity scaleMarksEntity:scaleMarksEntities){
                if (score <= Integer.valueOf(scaleMarksEntity.getScoreEnd()) && score >= Integer.valueOf(scaleMarksEntity.getScoreStart())){
                    resultMap0.put("结论", scaleMarksEntity.getSymptom());
                    resultJson.put("结论", scaleMarksEntity.getSymptom());
                    if (scaleMarksEntity.getImprovementSuggestions() != null){
                        resultMap0.put("建议", scaleMarksEntity.getImprovementSuggestions());
                        resultJson.put("建议", scaleMarksEntity.getImprovementSuggestions());
                    }
                }
            }
        }

        List<Map<String,String>> resultMapList = new ArrayList<>();
        resultMapList.add(resultMap0);

        JSONObject returnJson = new JSONObject(true);
        returnJson.put("resultMapList",resultMapList);
        //returnJson.put("scaleName",resultJson.getString("scaleName"));
        returnJson.put("resultJson",resultJson);

        return returnJson;
    }
}
