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.scaleresult.ScaleConstant;
import com.rf.psychological.scale.service.DimensionOrgService;
import com.rf.psychological.utils.Constant;

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 2021/7/20 15:55
 */
public class SCSQScale extends BaseScale{

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

    public  JSONObject scaleCalculate() throws Exception {
        //积极应对得分
        double score1 = 0;
        //消极应对得分
        double score2 = 0;
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject1 = jsonArray.getJSONObject(i);
            if (i <= 11){
                if (jsonObject1.getString("checkItems").equals("偶尔采取")) {
                    score1 += 1;
                } else if (jsonObject1.getString("checkItems").equals("有时采取")) {
                    score1 += 2;
                } else if (jsonObject1.getString("checkItems").equals("经常采取")) {
                    score1 += 3;
                }
            }else {
                if (jsonObject1.getString("checkItems").equals("偶尔采取")) {
                    score2 += 1;
                } else if (jsonObject1.getString("checkItems").equals("有时采取")) {
                    score2 += 2;
                } else if (jsonObject1.getString("checkItems").equals("经常采取")) {
                    score2 +=3;
                }
            }
        }

        DecimalFormat df   = new DecimalFormat("######0.00");
        score1 = Double.parseDouble(df.format(score1/12));
        score2 = Double.parseDouble(df.format(score2/8));

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

        //获取评分规则列表
        List<ScaleMarksEntity> scaleMarksEntities = (List<ScaleMarksEntity>) resultJson.get("scaleMarksEntities");
        //获取维度信息列表
        List<DimensionEntity> dimensionEntities = (List<DimensionEntity>) resultJson.get("dimensionEntities");
        //计算每个维度得分dimensionEntities
        double[] dimensionScore = {score1,score2};

        //将量表总维度根据维度名称进行分组
        Map<String, List<ScaleMarksEntity>> scaleMarksMap = scaleMarksEntities.stream().collect(Collectors.groupingBy(ScaleMarksEntity::getName));
        //返回值以及存数据库格式
        List<NewResultDto> newResultDtos = new ArrayList<>();

        Map<String, String> resultMap1 = new LinkedHashMap<>();
        double v = (score1 - 1.78) / 0.52 - ((score2 - 1.59) / 0.66);
        resultMap1.put("总分", String.valueOf(Double.parseDouble(df.format(v))));
        resultJson.put("总分", String.valueOf(Double.parseDouble(df.format(v))));

        BigDecimal scoreDecimal = new BigDecimal(df.format(v));
        //如果没有总分这一栏，需要手动赋值返回
        List<ScaleMarksEntity> totalScore = scaleMarksMap.get("总分");
        List<ScaleMarksEntity> totalScores = scaleMarksMap.get("无");
        if (totalScore == null) {
            if (totalScores == null){
                newResultDtos.add(new NewResultDto("总分", df.format(v), "无", "无",
                        "无", "无", "无", "无", "是"));
            }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(v), tempTotalScore.getSymptom(), tempTotalScore.getImprovementSuggestions(),
                                tempTotalScore.getFlag(), tempTotalScore.getReference(), tempTotalScore.getNameExplain(), tempTotalScore.getSuggestion(), tempTotalScore.getIsTotalScoreExplain()));
                        resultMap1.put("总分解释", tempTotalScore.getSymptom());
                        resultMap1.put("总分说明", tempTotalScore.getImprovementSuggestions());
                        resultMap1.put("总分解读", tempTotalScore.getNameExplain());
                        resultMap1.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(v), tempTotalScore.getSymptom(), tempTotalScore.getImprovementSuggestions(),
                            tempTotalScore.getFlag(), tempTotalScore.getReference(), tempTotalScore.getNameExplain(), tempTotalScore.getSuggestion(), tempTotalScore.getIsTotalScoreExplain()));
                    resultMap1.put("总分解释", tempTotalScore.getSymptom());
                    resultMap1.put("总分说明", tempTotalScore.getImprovementSuggestions());
                    resultMap1.put("总分解读", tempTotalScore.getNameExplain());
                    resultMap1.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, resultMap1, 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(resultMap1);


        Map<String ,Double> dimensionOrg = new HashMap<>();
        System.out.println("score1=="+score1+"     score2"+score2);
        dimensionOrg.put("8af178857b94d581017b94f27e16141c",score1);
        dimensionOrg.put("8af178857b94d581017b94f27e6d141d",score2);
        resultJson.put("dimensionScoreMap",dimensionOrg);

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

        return returnJson;
    }

    public static  WarnEntity createWarnEntry(String flag,  String institutionNo, String userId, String id, double score) {
        WarnEntity warn = new WarnEntity();

        warn.setFlag(flag);
        warn.setInstitutionNo(institutionNo);
        warn.setUserId(userId);
        warn.setDimensionId(id);
        warn.setScore(String.valueOf(score));
        return warn;
    }
}
