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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rf.psychological.utils.Constant;

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

/**
 * @author lpf
 * @description:军人心理应激自评问卷
 * @date 2021/3/10 17:17
 */
public class JRXLYJScale extends BaseScale {

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

    public JSONObject scaleCalculate() throws Exception {
        //原始分数
        double score = 0;
        int[] result = new int[jsonArray.size()];
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject1 = jsonArray.getJSONObject(i);
            if (jsonObject1.getString("checkItems").equals("没有")) {
                score += 1;
                result[i] = 1;
            } else if (jsonObject1.getString("checkItems").equals("有时")) {
                score += 2;
                result[i] = 2;
            } else if (jsonObject1.getString("checkItems").equals("经常")) {
                score += 3;
                result[i] = 3;
            }
        }
        double average = (double) score / result.length;
        double variance = Variance(result);
        score = 50 + 10 * (score - average) / variance;

        //得分列表
        Map<String, String> resultMap = new LinkedHashMap<>();
        resultMap.put("总分", String.valueOf(score));
        resultJson.put("总分", String.valueOf(score));


        if (score < 70.0) {
            resultMap.put("结论", "正常");
            resultJson.put("结论", "正常");
        } else if (score >= 70) {
            resultMap.put("结论", "心理应激程度较高。");
            resultJson.put("结论", "心理应激程度较高。");
        }

        List<Map<String, String>> resultMapList = new ArrayList<>();
        resultMapList.add(resultMap);
        JSONObject returnJson = new JSONObject(true);
        returnJson.put("resultMapList", resultMapList);
        returnJson.put("scaleName", Constant.SHEET_NAME_JRXLYJ);
        returnJson.put("resultJson", resultJson);

        return returnJson;
    }

    //计算方差
    public static double Variance(int[] x) {
        int m = x.length;
        double sum = 0;
        for (int i = 0; i < m; i++) {//求和
            sum += x[i];
        }
        double dAve = sum / m;//求平均值
        double dVar = 0;
        for (int i = 0; i < m; i++) {//求方差
            dVar += (x[i] - dAve) * (x[i] - dAve);
        }
        return dVar / m;
    }

}
