package com.rf.psychological.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rf.psychological.api.key.dao.model.KeyEntity;
import com.rf.psychological.api.key.service.KeyService;
import com.rf.psychological.base.rest.BaseController;
import com.rf.psychological.dao.dto.*;
import com.rf.psychological.dao.model.AnswerEntity;
import com.rf.psychological.dao.model.DimensionEntity;
import com.rf.psychological.file.excel.ExcelClass;
import com.rf.psychological.group.dao.model.GroupEntity;
import com.rf.psychological.group.service.GroupInfoService;
import com.rf.psychological.institution.model.InstitutionEntity;
import com.rf.psychological.institution.service.InstitutionAuthService;
import com.rf.psychological.institution.service.InstitutionService;
import com.rf.psychological.plan.dao.model.TestPlanEntity;
import com.rf.psychological.scale.dao.model.*;
import com.rf.psychological.scale.service.*;
import com.rf.psychological.security.RSAUtils;
import com.rf.psychological.security.SafetyProcess;
import com.rf.psychological.user.dao.model.UserEntity;
import com.rf.psychological.user.service.UserService;
import com.rf.psychological.utils.*;
import com.rf.psychological.wxpay.model.PromotionInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/v1/subject")
@Api(tags = "外部系统量表操作")
public class SubjectApi extends BaseController {

    @Autowired
    private InstitutionService institutionService;

    @Autowired
    private InstitutionAuthService institutionAuthService;

    @Autowired
    private ScaleService scaleService;

    @Autowired
    private UserRecordService userRecordService;

    @Autowired
    private UserService userService;

    @Autowired
    private SubjectService subjectService;

    @Autowired
    private AnswerService answerService;

    @Autowired
    private ScaleMarksService scaleMarksService;

    @Autowired
    private DimensionService dimensionService;

    @Autowired
    private DimensionOrgService dimensionOrgService;

    @Autowired
    private ScaleScoringVersion scaleScoringVersion;

    @Autowired
    private ScaleConfigService scaleConfigService;

    @Autowired
    private KeyService keyService;

    @Autowired
    private GroupInfoService groupInfoService;

    @ApiOperation(value = "外部系统获取量表列表接口",notes = "data参数包括：pageNum:页码, pageSize:条数,institutionNo:机构编号,subjectName:量表名称")
    @PostMapping("/getSubjectList")
    public Result getSubjectList(@RequestBody String params){
        try {
            String jsonParams = RSAUtils.decryptByPrivateKey3(params,RSAUtils.privateKeyStr);
            log.info("getSubjectList===="+jsonParams);
            JSONObject jsonObject =JSONObject.parseObject( jsonParams);
            if (!jsonObject.containsKey("institutionNo") ||  StringUtils.isEmpty(jsonObject.getString("institutionNo")) ) {
                return fail("", "机构编号不能为空");
            }
            String institutionNo = jsonObject.getString("institutionNo");
            if (!jsonObject.containsKey("subjectName")) {
                return fail("", "入参量表名称不存在");
            }
            String subjectName = jsonObject.getString("subjectName");
            if (!jsonObject.containsKey("pageNum") ||  StringUtils.isEmpty(jsonObject.getString("pageNum")) ) {
                return fail("", "页码不能为空");
            }
            int pageNum = jsonObject.getInteger("pageNum");
            if (!jsonObject.containsKey("pageSize") ||  StringUtils.isEmpty(jsonObject.getString("pageSize")) ) {
                return fail("", "条数不能为空");
            }
            int pageSize = jsonObject.getInteger("pageSize");
            //判断机构编号是否存在
            InstitutionEntity institutionEntity = this.institutionService.findByInstitutionNo(institutionNo);
            if (institutionEntity == null) {
                return fail("", "机构编号不存在！");
            }
            // 创建返回的json对象
            JSONObject resultJson = new JSONObject();
            // 创建量表信息json对象
            JSONArray resultData = new JSONArray();
            List<InstitutionAuthSubjectNameDto> byInstitutionNoAndName = this.institutionAuthService.getByInstitutionNoAndName(pageNum, pageSize, institutionNo, "0", subjectName,null);
            for (InstitutionAuthSubjectNameDto institutionAuthSubject : byInstitutionNoAndName) {
                JSONObject subjectObject = new JSONObject(true);
                subjectObject.put("flag",institutionAuthSubject.getFlag());
                subjectObject.put("name",institutionAuthSubject.getName());
                subjectObject.put("description",institutionAuthSubject.getDescription());
                resultData.add(subjectObject);
            }
            int num = this.institutionAuthService.getAllByTableInAuthAndSubInfoNum(institutionNo, "0", subjectName,null);
            resultJson.put("allNum",num);
            resultJson.put("resultData",resultData);
            log.info("resultJson===="+resultJson);
            //获取该机构编号下公钥
            KeyEntity keyEntity = keyService.find(institutionNo);
            if (keyEntity == null){
                return fail(null,"未获取到该机构下秘钥信息");
            }
            if(StringUtils.isEmpty(keyEntity.getPubKey())){
                return fail(null,"未获取到该机构下秘钥信息");
            }
            String encryptStr = RSAUtils.encryptByPublicKey3(resultJson.toJSONString(),keyEntity.getPubKey());
            return success(encryptStr);
        }catch (Exception e){
            e.printStackTrace();
            return fail();
        }
    }

    @ApiOperation(value = "外部系统获取量表详情接口",notes = "data参数包括：flag:量表唯一标识, institutionNo:机构编号")
    @PostMapping("/getSubject")
    public Result getSubject(@RequestBody String params){
        try {
            String jsonParams = RSAUtils.decryptByPrivateKey3(params,RSAUtils.privateKeyStr);
            log.info("getSubject===="+jsonParams);
            JSONObject jsonObject =JSONObject.parseObject( jsonParams);
            if (!jsonObject.containsKey("institutionNo") ||  StringUtils.isEmpty(jsonObject.getString("institutionNo")) ) {
                return fail("", "机构编号不能为空");
            }
            String institutionNo = jsonObject.getString("institutionNo");
            if (!jsonObject.containsKey("flag") ||  StringUtils.isEmpty(jsonObject.getString("flag")) ) {
                return fail("", "量表唯一标识不能为空");
            }
            String flag = jsonObject.getString("flag");
            //判断机构编号是否存在
            InstitutionEntity institutionEntity = this.institutionService.findByInstitutionNo(institutionNo);
            if (institutionEntity == null) {
                return fail("", "机构编号不存在！");
            }
            // 创建返回的json对象
            JSONArray resultJson = new JSONArray();
            List<ScaleEntity> scaleEntityList = this.scaleService.getScaleByFlagAndInstitutionNo(institutionNo, flag);
            for (ScaleEntity scaleEntity : scaleEntityList) {
                JSONObject scaleObject = new JSONObject(true);
                scaleObject.put("questionNo",scaleEntity.getQuestionNo());
                scaleObject.put("answer",scaleEntity.getAnswer());
                scaleObject.put("checkItems",scaleEntity.getCheckItems());
                scaleObject.put("questionType",scaleEntity.getQuestionType());
                resultJson.add(scaleObject);
            }
            log.info("resultJson===="+resultJson);
            //获取该机构编号下公钥
            KeyEntity keyEntity = keyService.find(institutionNo);
            if (keyEntity == null){
                return fail(null,"未获取到该机构下秘钥信息");
            }
            if(StringUtils.isEmpty(keyEntity.getPubKey())){
                return fail(null,"未获取到该机构下秘钥信息");
            }
            String encryptStr = RSAUtils.encryptByPublicKey3(resultJson.toJSONString(),keyEntity.getPubKey());
            return success(encryptStr);
        }catch (Exception e){
            e.printStackTrace();
            return fail();
        }
    }

    @ApiOperation(value = "外部系统量表测试分析接口",notes = "data参数包括：flag:量表唯一标识, userName:用户名, userId:外部用户唯一标识, institutionNo:机构编号, subjectResult:答题详情")
    @PostMapping("/analysis")
    public Result analysis(@RequestBody String params){
        try {
            String jsonParams = RSAUtils.decryptByPrivateKey3(params,RSAUtils.privateKeyStr);
            log.info("getSubject===="+jsonParams);
            JSONObject jsonObject =JSONObject.parseObject( jsonParams);
            if (!jsonObject.containsKey("institutionNo") ||  StringUtils.isEmpty(jsonObject.getString("institutionNo")) ) {
                return fail("", "机构编号不能为空");
            }
            String institutionNo = jsonObject.getString("institutionNo");
            if (!jsonObject.containsKey("userId") ||  StringUtils.isEmpty(jsonObject.getString("userId")) ) {
                return fail("", "外部用户唯一标识不能为空");
            }
            String userId = jsonObject.getString("userId");
            if (!jsonObject.containsKey("flag") ||  StringUtils.isEmpty(jsonObject.getString("flag")) ) {
                return fail("", "量表唯一标识不能为空");
            }
            String flag = jsonObject.getString("flag");
            if (!jsonObject.containsKey("userName") ||  StringUtils.isEmpty(jsonObject.getString("userName")) ) {
                return fail("", "用户名不能为空");
            }
            String phone = jsonObject.getString("userName");
            //判断机构编号是否存在
            InstitutionEntity institutionEntity = this.institutionService.findByInstitutionNo(institutionNo);
            if (institutionEntity == null) {
                return fail("", "机构编号不存在！");
            }
            //判断用户是否存在
            UserEntity userEntity = this.userService.findPhoneAndInstitutionNoAndRoleType(phone,institutionNo,Constant.DEFAULT_VALUE_ONE);
            if(userEntity == null){
                return fail("用户不存在");
            }
            String userName = userEntity.getPetName();
            String userBirthday = userEntity.getBirthday();
            String userSex = userEntity.getGender();
            if (userSex.equals("0")) {
                userSex = "男";
            } else {
                userSex = "女";
            }

            String testTime = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒").format(new Date());
            String fileName = userName + Constant.SPLIT_CHAR + userBirthday + Constant.SPLIT_CHAR + userSex + Constant.SPLIT_CHAR + testTime;
            String testResult = "";
            JSONArray jsonArray = jsonObject.getJSONArray("subjectResult");

            // 创建返回的json对象
            JSONObject resultJson = new JSONObject(true);
            //根据flag获取全部选项
            List<ScaleEntity> scaleEntities = this.scaleService.getScaleByFlag(flag);
            //根据flag获取全部答案
            List<AnswerEntity> answerEntities = this.answerService.getAnswerByFlag(flag);
            //根据flag获取全部评分规则
            List<ScaleMarksEntity> scaleMarksEntities = this.scaleMarksService.getScaleMarksByFlag(flag);
            //根据flag获取全部维度信息
            List<DimensionEntity> dimensionEntities = this.dimensionService.getDimensionByFlag(flag);
            //根据flag获取量表名称
            List<SubjectEntity> subjectEntities = this.subjectService.getSubjectByFlag(flag);
            resultJson.put("scaleEntities", scaleEntities);
            resultJson.put("answerEntities", answerEntities);
            resultJson.put("scaleMarksEntities", scaleMarksEntities);
            resultJson.put("dimensionEntities", dimensionEntities);
            //机构编号，用于预警信息判断
            resultJson.put("institutionNo",institutionNo);
            //用户id用于预警信息保存
            resultJson.put("userId",userEntity.getId());
            resultJson.put("dimensionOrgService",dimensionOrgService);
            //答题结果列表
            List<ScaleEntity> dataList = jsonArray.toJavaList(ScaleEntity.class);
            ScaleConfigEntity scaleConfigByFlag = scaleConfigService.findScaleConfigByFlag(flag);
            String className = (scaleConfigByFlag== null ?"com.rf.psychological.scale.resultBusiness.scaleResult.COMMONScale":scaleConfigByFlag.getResultConfig());
            Class<?> cls; // 取得Class对象
            try {
                cls = Class.forName(className);
                Constructor<?> cons = cls.getConstructor(JSONArray.class, JSONObject.class);
//            Object obj = cons.newInstance(); // 为构造方法传递参数
                Object obj = cons.newInstance(jsonArray, resultJson);
                //System.out.println(obj);
                //cls.getDeclaredMethods();
                Method method = null;
                //通过配置文件获取量表计分规则使用的版本
                ObjectMapper objectMapper = new ObjectMapper();
                String str = objectMapper.writeValueAsString(scaleScoringVersion.getVersionmap());
                HashMap mapScale = JSON.parseObject(str, HashMap.class);
                System.out.println(mapScale);
                Set<Map.Entry<String, String>> en = mapScale.entrySet();
                for(Map.Entry<String, String> entry : en) {
                    String[] flags = entry.getValue().split(", ");
                    for (String obtainFlag:flags){
                        System.out.println("flag:"+obtainFlag);
                        if (obtainFlag.equals(flag)){
                            method = cls.getDeclaredMethod(entry.getKey());
                            break;
                        }
                    }
                }
                if ( method == null){
                    method = cls.getDeclaredMethod("scaleCalculate");
                }
                //method = cls.getDeclaredMethod("scaleCalculate");
                resultJson = (JSONObject) method.invoke(obj);
            } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InstantiationException |
                    InvocationTargetException e) {
                e.printStackTrace();
            }
            resultJson.getJSONObject("resultJson").remove("scaleEntities");
            resultJson.getJSONObject("resultJson").remove("answerEntities");
            resultJson.getJSONObject("resultJson").remove("scaleMarksEntities");
            resultJson.getJSONObject("resultJson").remove("dimensionEntities");

            resultJson.getJSONObject("resultJson").remove("institutionNo");
            resultJson.getJSONObject("resultJson").remove("userId");
            resultJson.getJSONObject("resultJson").remove("dimensionOrgService");

            if (resultJson.getJSONObject("resultJson").containsKey("resultJson") && resultJson.getJSONObject("resultJson").get("测试结果指导").equals("请认真按照实际情况如实回答")) {
                resultJson = resultJson.getJSONObject("resultJson");
                return success(resultJson, "完成");
            }
            fileName = fileName + "-" + subjectEntities.get(0).getName() + ".xlsx";
            //导出文件
            ExcelUtil.createExcelFile(ScaleEntity.class, dataList, (List<Map<String, String>>) resultJson.get("resultMapList"), new ExcelClass().contentExcel(), fileName, subjectEntities.get(0).getName());

            //计算结果
            JSONArray dbJsonList = new JSONArray();
            JSONObject dbJson = new JSONObject(true);
            boolean versionFlag = false;
            Map<String, Object> newResultJson = null;
            if (!resultJson.containsKey("newResultJson")) {
                dbJson.put("version", 1.0);
                dbJson.put("newTableContext", "");
            } else {
                newResultJson = (Map<String, Object>) resultJson.get("newResultJson");
                dbJson.put("version", 2.0);
                dbJson.put("newTableContext", newResultJson);
                versionFlag = true;
            }

            resultJson = resultJson.getJSONObject("resultJson");
            List<WarnEntity> warnEntityList = new ArrayList<WarnEntity>();
            if(resultJson.containsKey("warnEntityList")) {
                warnEntityList = resultJson.getJSONArray("warnEntityList").toJavaList(WarnEntity.class);
                resultJson.remove("warnEntityList");
            }
            // 获取JSON第一层所有的key
            Set<String> keys = resultJson.keySet();

            //列名
            List colNames = new ArrayList();
            colNames.add("项目");
            colNames.add("内容");
            dbJson.put("colNames", colNames);
            JSONArray tableContext = new JSONArray();

            // 获取第一层每个key对应的值 的类型
            for (String key : keys) {
                //列值
                List colValue = new ArrayList();
                colValue.add(resultJson.get(key));
                JSONObject row = new JSONObject();
                row.put("name", key);
                row.put("value", colValue);
                tableContext.add(row);
            }

            dbJson.put("tableContext", tableContext);

            dbJsonList.add(dbJson);

            //测试记录
            int i = 1;
            // 获取第一层每个key对应的值 的类型
            for (String key : keys) {
                if (i == keys.size()) {
                    testResult += key + ":" + resultJson.get(key);
                } else {
                    testResult += key + ":" + resultJson.get(key) + ";";
                }
                i++;
            }
            String filePath;
            filePath = "./心理检测/检测结果/" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "/" + subjectEntities.get(0).getName() + "/" + fileName;
            UserRecordEntity userRecordEntity = testRecord(flag, userId, institutionNo, testTime, filePath, JSON.toJSONString(dbJsonList, SerializerFeature.DisableCircularReferenceDetect), subjectEntities.get(0).getName(), JSON.toJSONString(dataList, SerializerFeature.DisableCircularReferenceDetect), testResult, Constant.DEFAULT_VALUE_ZERO);

            // 创建返回的json对象
            JSONObject resultJsonObject = new JSONObject();
            resultJsonObject.put("resultId",userRecordEntity.getId());
            log.info("resultJsonObject===="+resultJsonObject);
            //获取该机构编号下公钥
            KeyEntity keyEntity = keyService.find(institutionNo);
            if (keyEntity == null){
                return fail(null,"未获取到该机构下秘钥信息");
            }
            if(StringUtils.isEmpty(keyEntity.getPubKey())){
                return fail(null,"未获取到该机构下秘钥信息");
            }
            String encryptStr = RSAUtils.encryptByPublicKey3(resultJsonObject.toJSONString(),keyEntity.getPubKey());
            return success(encryptStr);
        }catch (Exception e){
            e.printStackTrace();
            return fail();
        }
    }

    private UserRecordEntity testRecord(String flag, String phone, String institutionNo, String testTime, String fileName, String testResult, String name, String dataList, String testResults, String testPlanId) {
        //根据flag记录测试数
        this.subjectService.addTestNum(flag);
        //添加用户测试记录
        UserRecordEntity userRecordEntity = new UserRecordEntity();
        userRecordEntity.setFlag(flag);
        userRecordEntity.setPhone(phone);
        userRecordEntity.setInstitutionNo(institutionNo);
        userRecordEntity.setTestDate(testTime);
        userRecordEntity.setTestResult(testResult);
        userRecordEntity.setType("0");
        userRecordEntity.setFileName(fileName);
        userRecordEntity.setName(name);
        userRecordEntity.setTestRecord(dataList);
        userRecordEntity.setTestResults(testResults);
        if (testPlanId == null || testPlanId.equals("")) {
            userRecordEntity.setTestPlanId("0");
        } else {
            userRecordEntity.setTestPlanId(testPlanId);
        }
        this.userRecordService.save(userRecordEntity);
        return userRecordEntity;
    }

    @ApiOperation(value = "外部系统获取量表测试分析结果接口",notes = "data参数包括：resultId:测试结果唯一标识,userId:外部用户唯一标识, institutionNo:机构编号")
    @PostMapping("/getSubjectResult")
    public Result getSubjectResult(@RequestBody String params){
        try {
            String jsonParams = RSAUtils.decryptByPrivateKey3(params,RSAUtils.privateKeyStr);
            JSONObject jsonObject =JSONObject.parseObject(jsonParams);
            log.info("getSubject===="+jsonParams);
            if (!jsonObject.containsKey("institutionNo") ||  StringUtils.isEmpty(jsonObject.getString("institutionNo")) ) {
                return fail("", "机构编号不能为空");
            }
            String institutionNo = jsonObject.getString("institutionNo");
            if (!jsonObject.containsKey("userId") ||  StringUtils.isEmpty(jsonObject.getString("userId")) ) {
                return fail("", "外部用户唯一标识不能为空");
            }
            String userId = jsonObject.getString("userId");
            if (!jsonObject.containsKey("resultId") ||  StringUtils.isEmpty(jsonObject.getString("resultId")) ) {
                return fail("", "测试结果唯一标识不能为空");
            }
            String resultId = jsonObject.getString("resultId");
            //判断机构编号是否存在
            InstitutionEntity institutionEntity = this.institutionService.findByInstitutionNo(institutionNo);
            if (institutionEntity == null) {
                return fail("", "机构编号不存在！");
            }
            // 创建返回的json对象
            JSONObject resultJson = new JSONObject();
            UserRecordEntity userRecordEntity = this.userRecordService.getuserRecordByIdAndInstitutionNoAndPhone(resultId,userId,institutionNo);
            if (userRecordEntity != null){
                resultJson.put("name",userRecordEntity.getName());
                resultJson.put("testDate",userRecordEntity.getTestDate());
                resultJson.put("testResult",userRecordEntity.getTestResult());
            }
            log.info("resultJson===="+resultJson);
            //获取该机构编号下公钥
            KeyEntity keyEntity = keyService.find(institutionNo);
            if (keyEntity == null){
                return fail(null,"未获取到该机构下秘钥信息");
            }
            if(StringUtils.isEmpty(keyEntity.getPubKey())){
                return fail(null,"未获取到该机构下秘钥信息");
            }
            String encryptStr = RSAUtils.encryptByPublicKey3(resultJson.toJSONString(),keyEntity.getPubKey());
            return success(encryptStr);
        }catch (Exception e){
            e.printStackTrace();
            return fail();
        }
    }

    @ApiOperation(value = "外部系统查询机构下所有用户已经做的测试记录",notes = "data参数包括：pageNum:页码, pageSize:条数,institutionNo:机构编号,type:类型（0量表；1认知任务）,searchKey:查询参数")
    @PostMapping("/getUserRecording")
    public Result getUserRecording(@RequestBody String params) {
        try {
            String jsonParams = RSAUtils.decryptByPrivateKey3(params,RSAUtils.privateKeyStr);
            JSONObject jsonObject =JSONObject.parseObject(jsonParams);
            log.info("getUserRecording===="+jsonParams);
            if (!jsonObject.containsKey("institutionNo") ||  StringUtils.isEmpty(jsonObject.getString("institutionNo")) ) {
                return fail("", "机构编号不能为空");
            }
            String institutionNo = jsonObject.getString("institutionNo");
            if (!jsonObject.containsKey("type") ||  StringUtils.isEmpty(jsonObject.getString("type")) ) {
                return fail("", "类型不能为空");
            }
            String type = jsonObject.getString("type");
            if (!jsonObject.containsKey("pageNum") ||  StringUtils.isEmpty(jsonObject.getString("pageNum")) ) {
                return fail("", "页码不能为空");
            }
            int pageNum = jsonObject.getInteger("pageNum");
            if (!jsonObject.containsKey("pageSize") ||  StringUtils.isEmpty(jsonObject.getString("pageSize")) ) {
                return fail("", "条数不能为空");
            }
            int pageSize = jsonObject.getInteger("pageSize");
            String searchKey = "";
            if (jsonObject.containsKey("searchKey") && !StringUtils.isEmpty(jsonObject.getString("searchKey")) ) {
                searchKey = jsonObject.getString("searchKey");
            }
            if (pageSize == 0) {
                pageSize = 20;
            }
            String beginFormat = "", endFormat = "";
            int num;
            List<InstitutionRecordingDTO> institutionUserRecordingList = this.userRecordService.getInstitutionUserRecording(pageNum, pageSize, type, institutionNo, searchKey, beginFormat, endFormat);
            num = this.userRecordService.allCountByInstitutionNo(institutionNo, type, searchKey, "", "");
            log.info("institutionUserRecordingList:" + JSONObject.toJSONString(institutionUserRecordingList));
            JSONObject returnJsonObject = new JSONObject();
            returnJsonObject.put("institutionUserRecordingList", institutionUserRecordingList);
            returnJsonObject.put("allNum", num);
            //获取该机构编号下公钥
            KeyEntity keyEntity = keyService.find(institutionNo);
            if (keyEntity == null){
                return fail(null,"未获取到该机构下秘钥信息");
            }
            if(StringUtils.isEmpty(keyEntity.getPubKey())){
                return fail(null,"未获取到该机构下秘钥信息");
            }
            String encryptStr = RSAUtils.encryptByPublicKey3(returnJsonObject.toJSONString(),keyEntity.getPubKey());
            return success(encryptStr);
        }catch (Exception e){
            e.printStackTrace();
            return fail();
        }
    }

    @ApiOperation(value = "外部系统查询机构下测试量表下的用户",notes = "data参数包括：pageNum:页码, pageSize:条数,institutionNo:机构编号,name:量表或认知任务名称,searchKey:查询参数")
    @PostMapping("/getTestUser")
    public Result getTestUser(@RequestBody String params) {
        try {
            String jsonParams = RSAUtils.decryptByPrivateKey3(params,RSAUtils.privateKeyStr);
            JSONObject jsonObject =JSONObject.parseObject( jsonParams);
            log.info("getTestUser===="+jsonParams);
            if (!jsonObject.containsKey("institutionNo") ||  StringUtils.isEmpty(jsonObject.getString("institutionNo")) ) {
                return fail("", "机构编号不能为空");
            }
            String institutionNo = jsonObject.getString("institutionNo");
            if (!jsonObject.containsKey("name") ||  StringUtils.isEmpty(jsonObject.getString("name")) ) {
                return fail("", "量表或认知任务名称不能为空");
            }
            String name = jsonObject.getString("name");
            if (!jsonObject.containsKey("pageNum") ||  StringUtils.isEmpty(jsonObject.getString("pageNum")) ) {
                return fail("", "页码不能为空");
            }
            int pageNum = jsonObject.getInteger("pageNum");
            if (!jsonObject.containsKey("pageSize") ||  StringUtils.isEmpty(jsonObject.getString("pageSize")) ) {
                return fail("", "条数不能为空");
            }
            int pageSize = jsonObject.getInteger("pageSize");
            String searchKey = "";
            if (jsonObject.containsKey("searchKey") && !StringUtils.isEmpty(jsonObject.getString("searchKey")) ) {
                searchKey = jsonObject.getString("searchKey");
            }
            if (pageSize == 0) {
                pageSize = 20;
            }
            GroupEntity entity =this.groupInfoService.findGroupByInstitutionNoAndName(Constant.LAN_INSTITUTION_CODE,Constant.DEFAULT_GROUP_NAME);
            if (entity == null ){
                return fail("", "机构下无默认分组！");
            }
            String groupId = entity.getId();
            String beginFormat = "", endFormat = "";
            int num;
            //添加分组过滤
            List<InstitutionRecordingUserDTO> institutionUserRecordingList = this.userRecordService.getInstitutionRecording(pageNum, pageSize, institutionNo, name, searchKey, beginFormat, endFormat, groupId);
            num = this.userRecordService.allCountInstitutionRecording(institutionNo, name, searchKey, beginFormat, endFormat, groupId);
            List<InstitutionRecordingUserApiDTO> institutionRecordingUserApiDTOList = new ArrayList<>();
            for (InstitutionRecordingUserDTO institutionRecordingUserDTO : institutionUserRecordingList) {
                InstitutionRecordingUserApiDTO institutionRecordingUserApiDTO = new InstitutionRecordingUserApiDTO();
                institutionRecordingUserApiDTO.setPhone(institutionRecordingUserDTO.getPhone());
                institutionRecordingUserApiDTO.setPetName(institutionRecordingUserDTO.getPetName());
                institutionRecordingUserApiDTO.setGender(institutionRecordingUserDTO.getGender());
                institutionRecordingUserApiDTO.setBirthday(institutionRecordingUserDTO.getBirthday());
                institutionRecordingUserApiDTO.setTestDate(institutionRecordingUserDTO.getTestDate());
                institutionRecordingUserApiDTO.setInstitutionNo(institutionRecordingUserDTO.getInstitutionNo());
                institutionRecordingUserApiDTO.setId(institutionRecordingUserDTO.getId());
                institutionRecordingUserApiDTOList.add(institutionRecordingUserApiDTO);
            }
            JSONObject returnJsonObject = new JSONObject();
            returnJsonObject.put("institutionUserRecordingList", institutionRecordingUserApiDTOList);
            returnJsonObject.put("allNum", num);
            //获取该机构编号下公钥
            KeyEntity keyEntity = keyService.find(institutionNo);
            if (keyEntity == null){
                return fail(null,"未获取到该机构下秘钥信息");
            }
            if(StringUtils.isEmpty(keyEntity.getPubKey())){
                return fail(null,"未获取到该机构下秘钥信息");
            }
            String encryptStr = RSAUtils.encryptByPublicKey3(returnJsonObject.toJSONString(),keyEntity.getPubKey());
            return success(encryptStr);
        }catch (Exception e){
            e.printStackTrace();
            return fail();
        }
    }

    /**
     * 查询某用户所有测试记录
     * @param params
     * @return
     */
    @PostMapping("/getUserAllResult")
    @ApiOperation(value = "外部系统查询某用户所有测试记录接口",notes = "json字符串形式传参（加密）,data参数包括:phone:账号或电话,institutionNo:机构编号,pageNum:页码, pageSize:条数,searchKey:查询参数")
    public Result getUserAllResult(@RequestBody String params){
        try {
            String jsonParams = RSAUtils.decryptByPrivateKey3(params,RSAUtils.privateKeyStr);
            JSONObject jsonObject =JSONObject.parseObject(jsonParams);
            log.info("getUserAllResult===="+jsonParams);
            if (!jsonObject.containsKey("phone") ||  StringUtils.isEmpty(jsonObject.getString("phone")) ) {
                return fail("", "账号不能为空");
            }
            String phone = jsonObject.getString("phone");
            log.info("phone: " + phone);
            if (!jsonObject.containsKey("institutionNo") || StringUtils.isEmpty(jsonObject.getString("institutionNo")) ) {
                return fail("", "机构编号");
            }
            String institutionNo = jsonObject.getString("institutionNo");
            log.info("institutionNo: " + institutionNo);
            if (!jsonObject.containsKey("pageNum") ||  StringUtils.isEmpty(jsonObject.getString("pageNum")) ) {
                return fail("", "页码不能为空");
            }
            int pageNum = jsonObject.getInteger("pageNum");
            if (!jsonObject.containsKey("pageSize") ||  StringUtils.isEmpty(jsonObject.getString("pageSize")) ) {
                return fail("", "条数不能为空");
            }
            int pageSize = jsonObject.getInteger("pageSize");
            String searchKey = "";
            if (jsonObject.containsKey("searchKey") && !StringUtils.isEmpty(jsonObject.getString("searchKey")) ) {
                searchKey = jsonObject.getString("searchKey");
            }
            if (pageSize == 0) {
                pageSize = 20;
            }

            Page<UserRecordsDto> userRecording = userRecordService.getUserRecording(pageNum, pageSize, phone, institutionNo, searchKey);
            JSONArray jsonArray = new JSONArray();
            for (UserRecordsDto userRecord : userRecording){
                JSONObject object = new JSONObject(true);
                object.put("name",userRecord.getName());
                object.put("testDate",userRecord.getTestDate());
                object.put("testResult",userRecord.getTestResult());
                jsonArray.add(object);
            }
            JSONObject returnJsonObject = new JSONObject();
            returnJsonObject.put("testResultList", jsonArray);
            returnJsonObject.put("allNum", userRecording.getTotalElements());
            //获取该机构编号下公钥
            KeyEntity keyEntity = keyService.find(institutionNo);
            if (keyEntity == null){
                return fail(null,"未获取到该机构下秘钥信息");
            }
            if(StringUtils.isEmpty(keyEntity.getPubKey())){
                return fail(null,"未获取到该机构下秘钥信息");
            }
            String encryptStr = RSAUtils.encryptByPublicKey3(returnJsonObject.toJSONString(),keyEntity.getPubKey());
            return success(encryptStr);
        }catch (Exception e){
            e.printStackTrace();
            return fail();
        }
    }

}
