package com.rf.psychological.user.rest;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.rf.psychological.base.rest.BaseController;
import com.rf.psychological.dao.model.AnswerEntity;
import com.rf.psychological.dao.model.DimensionEntity;
import com.rf.psychological.enums.UserRole;
import com.rf.psychological.group.dao.model.GroupEntity;
import com.rf.psychological.group.service.GroupInfoService;
import com.rf.psychological.module.index.service.IndexService;
import com.rf.psychological.scale.dao.model.ScaleEntity;
import com.rf.psychological.scale.dao.model.ScaleMarksEntity;
import com.rf.psychological.scale.dao.model.SubjectEntity;
import com.rf.psychological.scale.service.*;
import com.rf.psychological.security.DESede;
import com.rf.psychological.user.dao.model.UserEntity;
import com.rf.psychological.enums.UserStatus;
import com.rf.psychological.institution.model.InstitutionEntity;
import com.rf.psychological.institution.service.InstitutionService;
import com.rf.psychological.opLog.annotation.OperationLogAnnotation;
import com.rf.psychological.security.AesEncryptUtils;
import com.rf.psychological.security.SafetyProcess;
import com.rf.psychological.user.service.SystemService;
import com.rf.psychological.user.service.UserService;
import com.rf.psychological.utils.Constant;
import com.rf.psychological.utils.JWTUtil;
import com.rf.psychological.utils.Result;
import com.rf.psychological.utils.SnowFlakeUtil;
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.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.SpringApplicationEvent;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.management.relation.RoleStatus;
import javax.servlet.http.HttpServletRequest;

import java.util.List;
import java.util.concurrent.TimeUnit;

import static cn.hutool.core.date.DatePattern.PURE_DATETIME_PATTERN;

/**
 * @Description: 后台首页、登录、版本等接口
 * @Author: zsf
 * @Date: 2022/7/4
 */
@Slf4j
@RestController
@RequestMapping("/system")
@Api(tags = "后台首页、登录、版本等接口")
public class SystemController extends BaseController {

    @Autowired
    private SystemService systemService;

    @Autowired
    private UserService userService;

    @Autowired
    private InstitutionService institutionService;


    @Autowired
    private GroupInfoService groupInfoService;

    @Autowired
    private ScaleMarksService scaleMarksService;
    @Autowired
    private AnswerService answerService;
    @Autowired
    private SubjectService subjectService;
    @Autowired
    private DimensionService dimensionService;
    @Autowired
    private ScaleService scaleService;

    @Autowired
    private IndexService indexService;



    @Value("${spring.profiles.active}")
    private String profileValue;

    @Autowired
    private Environment env;

    @Autowired
    private StringRedisTemplate redisTemplate;
    @GetMapping("/getVersion")
    @SafetyProcess
    public Result getSystemVersion(){
        String value = env.getActiveProfiles()[0];
        return success(systemService.getSystemVersion(),profileValue);
    }
    @GetMapping("/temporaryUser")
    @SafetyProcess
    public Result temporaryUser(){
       try {
           //注册
           UserEntity userEntity = new UserEntity();
           userEntity.setPassword("-");
           userEntity.setGId(this.groupInfoService.findGroupByInstitutionNoAndName(Constant.WEB_INSTITUTION_CODE,Constant.DEFAULT_GROUP_NAME).getId());
           userEntity.setInstitutionName(Constant.WEB_INSTITUTION_NAME);
           userEntity.setInstitutionNo(Constant.WEB_INSTITUTION_CODE);
           userEntity.setUserStatus(Constant.USER_STATUS_NORMAL);
           userEntity.setBirthday("-");
           userEntity.setGender("-");
           userEntity.setPetName("游离用户");
           userEntity.setProfession("-");
           userEntity.setAdditionInfo("游离用户");
           userEntity.setPhone(SnowFlakeUtil.getNextId());
           userEntity.setRoleType(UserRole.COMMON.getType());
           userEntity = this.userService.save(userEntity);
           JSONObject resultJson = new JSONObject();
           resultJson.put("token", JWTUtil.getTokenByUserInfo(userEntity));
           resultJson.put("user",userEntity);
           resultJson.put("type",userEntity.getRoleType());
           log.info("响应消息："+resultJson.toJSONString());
           return success(resultJson);
       }catch (Exception e){
           log.error(e.getMessage());
           return fail();
       }
    }


    /**
     * 注册用户
     * @param jsonParam
     * @return
     */
    @PostMapping("/registerUser")
    @ApiOperation(value = "用户注册",notes = "json字符串形式传参（加密）,data参数包括:data:注册用户基本信息《birthday：生日，gender:性别，password:密码，roleType:角色，institutionNo:机构编号，phone:账号或电话》，authCode:验证码（公网版必填）")
    @SafetyProcess
    public Result registerUser(@RequestBody String jsonParam){
        try {
            String data = AesEncryptUtils.decrypt(JSONObject.parseObject(jsonParam).getString("data"));
            JSONObject jsonData = JSONObject.parseObject(data);
            JSONObject jsonUserEntity =jsonData.getJSONObject("data");
            UserEntity userEntity = jsonUserEntity.toJavaObject(UserEntity.class);
            userEntity.setModelPhone(Constant.DEFAULT_VALUE_ZERO);
            String institutionNo = userEntity.getInstitutionNo();
            if (StringUtils.isEmpty(institutionNo)){
                return fail("","机构编号不能为空");
            }
            //判断机构编号是否存在
            InstitutionEntity institutionEntity = this.institutionService.findByInstitutionNo(institutionNo);
            if (institutionEntity == null) {
                return fail("", "机构编号不存在！");
            }
            //添加校验是否开启注册校验或已达到上限值
            String isRegistrantValue = institutionEntity.getIsRegistrantsNum()==null?Constant.DEFAULT_VALUE_ZERO:institutionEntity.getIsRegistrantsNum().toString();
            if (Constant.DEFAULT_VALUE_ONE.equals(isRegistrantValue)){
                int userCount = this.indexService.findUserCount(institutionNo);
                if (userCount  >= institutionEntity.getRegistrantsNum()){
                    return fail(null,"注册人数已达到上限，请联系机构管理员");
                }
            }
            userEntity.setInstitutionName(institutionEntity.getInstitutionName());
            if (UserRole.COMMON.getType().equals(userEntity.getRoleType())){
                GroupEntity entity =this.groupInfoService.findGroupByInstitutionNoAndName(institutionNo,Constant.DEFAULT_GROUP_NAME);
                if (entity == null ){
                    return fail("", "机构下无默认分组！");
                }
                userEntity.setGId(entity.getId());
            }
            //区分是否需要验证码
            if (Constant.WEB_INSTITUTION_CODE.equals(userEntity.getInstitutionNo())){
                String authCode = jsonData.getString("authCode");
                if (StringUtils.isEmpty(authCode)){
                    return fail("","验证码不能为空");
                }
                String phone = userEntity.getPhone();
                String temp = redisTemplate.opsForValue().get("AUTH_CODE_"+phone);
                if(StringUtils.isBlank(temp)){
                    return fail("请重新获取验证码");
                }
                if (!temp.equals(authCode)) {
                    return fail("", "验证码错误");
                }
                userEntity.setUserStatus(UserStatus.PASS.getType());
            }
            UserEntity userInfo = this.userService.findPhoneAndInstitutionNoAndRoleType(userEntity.getPhone(), userEntity.getInstitutionNo(),userEntity.getRoleType());
            if (userInfo == null) {
                if (Constant.LAN_INSTITUTION_CODE.equals(userEntity.getInstitutionNo())){
                    userEntity.setUserStatus(Constant.USER_STATUS_NORMAL);
                }
                userEntity.setPassword(DigestUtils.md5DigestAsHex(userEntity.getPassword().getBytes()));
                this.userService.save(userEntity);
                return success();
            } else {
                return fail("", "账号已注册");
            }
        }catch (Exception e){
            e.printStackTrace();
            return fail();
        }
    }
    @SafetyProcess
    @ApiOperation(value = "系统登录接口",notes = "data参数包括：phone:账号, password:密码,institutionNo:机构编号,roleType:用户角色,authCode:密码,verification:验证信息《beginTime:时间,authCode:验证码,phone:电话》")
    @PostMapping("/login")
    public Result login(HttpServletRequest request, @RequestBody String jsonParams){
        try {
            JSONObject jsonObject =JSONObject.parseObject( AesEncryptUtils.decrypt(JSONObject.parseObject(jsonParams).getString("data")));
            log.info("jsonObject: " + jsonObject.toString());
            if (!jsonObject.containsKey("institutionNo") || !jsonObject.containsKey("roleType") ||  StringUtils.isEmpty(jsonObject.getString("institutionNo")) || StringUtils.isEmpty( jsonObject.getString("roleType") )) {
                return fail("", "机构编号和用户角色不能为空");
            }
            String institutionNo = jsonObject.getString("institutionNo");
            String roleType = jsonObject.getString("roleType");


            if (!jsonObject.containsKey("phone") || StringUtils.isEmpty(jsonObject.getString("phone")) ) {
                return fail("", "账号不能为空");
            }
            String phone = jsonObject.getString("phone");
            log.info("phone: " + phone);
            //判断机构编号是否存在
            InstitutionEntity institutionEntity = this.institutionService.findByInstitutionNo(institutionNo);
            log.info("institutionEntity: " + institutionEntity);
            if (institutionEntity == null) {
                return fail("", "机构编号不存在！");
            }
            UserEntity userEntity = this.userService.findPhoneAndInstitutionNoAndRoleType(phone, institutionNo,roleType);

            log.info("userEntity: " + userEntity);
            //如果是公网版并且验证码登录
            if (Constant.WEB_INSTITUTION_CODE.equals(institutionNo) && jsonObject.containsKey("authCode")){
                if (userEntity == null) {
                    return fail(null, "用户不存在");
                }
                String authCode = jsonObject.getString("authCode");
                if (StringUtils.isEmpty(authCode)){
                    return fail("","验证码不能为空");
                }
                String temp = redisTemplate.opsForValue().get("AUTH_CODE_" + phone);
                if(StringUtils.isBlank(temp)){
                    return fail("", "验证码已失效");
                }
                if (temp.equals(authCode)) {
                    //生成token
                    userEntity.setPassword(null);
                    String token = JWTUtil.getTokenByUserInfo(userEntity);
                    // 创建返回的json对象
                    JSONObject resultJson = new JSONObject();
                    resultJson.put("user", userEntity);
                    resultJson.put("type", userEntity.getRoleType());
                    resultJson.put("token", token);
                    request.getSession().setAttribute("user", userEntity);
                    return success(resultJson);
                } else {
                    return fail("", "验证码错误");
                }
            }else if ("lan".equals(profileValue)){
                if (!jsonObject.containsKey("password") || StringUtils.isEmpty(  jsonObject.getString("password") )) {
                    return fail("", "密码不能为空");
                }
                String password = jsonObject.getString("password");
                if (userEntity == null) {
                    if (Constant.LAN_INSTITUTION_CODE.equals(institutionNo)){
                        return fail(null, "账号或密码错误");
                    }
                    return fail(null, "账号错误");
                }
                String userStatus = userEntity.getUserStatus();
                if (UserStatus.AUDIT.getType().equals(userStatus)||UserStatus.UPDATE.getType().equals(userStatus)){
                    return fail(null, "用户未审核，请联系管理员");
                }
                if (userEntity.getPassword().equals(password)) {
                    //生成token
                    userEntity.setPassword(null);
                    String token = JWTUtil.getTokenByUserInfo(userEntity);
                    // 创建返回的json对象
                    JSONObject resultJson = new JSONObject();
                    resultJson.put("user", userEntity);
                    resultJson.put("type", userEntity.getRoleType());
                    resultJson.put("token", token);
                    request.getSession().setAttribute("user", userEntity);
                    return success(resultJson);
                } else {
                    return fail(null, "账号或密码错误");
                }
            }else {
                if (!jsonObject.containsKey("password") || StringUtils.isEmpty(  jsonObject.getString("password") )) {
                    return fail("", "密码不能为空");
                }
                String password = jsonObject.getString("password");
                if (userEntity == null) {
                    if (Constant.LAN_INSTITUTION_CODE.equals(institutionNo)){
                        return fail(null, "账号或密码错误");
                    }
                    return fail(null, "机构编号或账号错误");
                }
                String userStatus = userEntity.getUserStatus();
                if (UserStatus.AUDIT.getType().equals(userStatus)||UserStatus.UPDATE.getType().equals(userStatus)){
                    return fail(null, "用户未审核，请联系管理员");
                }
                if (userEntity.getPassword().equals(password)) {
                    //生成token
                    userEntity.setPassword(null);
                    String redisToken = redisTemplate.opsForValue().get("session:"+userEntity.getInstitutionNo()+":"+userEntity.getPhone()+":"+userEntity.getRoleType());
                    String token = redisToken;

                    //验证token是否有效
                    try {
                        JWTUtil.verify(token);
                    }catch (Exception e){
                        e.printStackTrace();
                        token = JWTUtil.getTokenByUserInfo(userEntity);
                        redisTemplate.opsForValue().set("session:"+userEntity.getInstitutionNo()+":"+userEntity.getPhone()+":"+userEntity.getRoleType(),token,5, TimeUnit.DAYS);
                    }

                    // 创建返回的json对象
                    JSONObject resultJson = new JSONObject();
                    resultJson.put("user", userEntity);
                    resultJson.put("type", userEntity.getRoleType());
                    resultJson.put("token", token);
                    request.getSession().setAttribute("user", userEntity);
                    return success(resultJson);
                } else {
                    return fail(null, "账号或密码错误");
                }
            }

        }catch (Exception e){
            e.printStackTrace();
            return fail();
        }
    }


    @SafetyProcess
    @ApiOperation(value = "系统登录接口",notes = "data参数包括：phone:账号,institutionNo:机构编号,roleType:用户角色,authCode:密码,verification:验证信息《beginTime:时间,authCode:验证码,phone:电话》")
    @PostMapping("/loginH5")
    public Result loginH5(HttpServletRequest request, @RequestBody String jsonParams){
        try {
            JSONObject jsonObject =JSONObject.parseObject( AesEncryptUtils.decrypt(JSONObject.parseObject(jsonParams).getString("data")));
            log.info("jsonObject: " + jsonObject.toString());
            if (!jsonObject.containsKey("institutionNo") || !jsonObject.containsKey("roleType") ||  StringUtils.isEmpty(jsonObject.getString("institutionNo")) || StringUtils.isEmpty( jsonObject.getString("roleType") )) {
                return fail("", "机构编号和用户角色不能为空");
            }
            String institutionNo = jsonObject.getString("institutionNo");
            String roleType = jsonObject.getString("roleType");
            if (!jsonObject.containsKey("phone") || StringUtils.isEmpty(jsonObject.getString("phone")) ) {
                return fail("", "账号不能为空");
            }
            String phone = jsonObject.getString("phone");
            log.info("phone: " + phone);
            //判断机构编号是否存在
            InstitutionEntity institutionEntity = this.institutionService.findByInstitutionNo(institutionNo);
            log.info("institutionEntity: " + institutionEntity);
            if (institutionEntity == null) {
                return fail("", "机构编号不存在！");
            }
            UserEntity userEntity = this.userService.findPhoneAndInstitutionNoAndRoleType(phone, institutionNo,roleType);
            log.info("userEntity: " + userEntity);
            //如果是公网版并且验证码登录
            if (userEntity == null) {
                userEntity = new UserEntity();
                userEntity.setPassword(DigestUtils.md5DigestAsHex(Constant.DEFAULT_PASSWORD.getBytes()));
                userEntity.setGId(this.groupInfoService.findGroupByInstitutionNoAndName(Constant.WEB_INSTITUTION_CODE,Constant.DEFAULT_GROUP_NAME).getId());
                userEntity.setInstitutionName(Constant.WEB_INSTITUTION_NAME);
                userEntity.setInstitutionNo(Constant.WEB_INSTITUTION_CODE);
                userEntity.setUserStatus(Constant.USER_STATUS_NORMAL);
                userEntity.setBirthday("-");
                userEntity.setGender("-");
                userEntity.setPetName(phone);
                userEntity.setProfession("-");
                userEntity.setPhone(phone);
                userEntity.setRoleType(UserRole.COMMON.getType());
                userEntity = this.userService.save(userEntity);
            }
            String authCode = jsonObject.getString("authCode");
            if (StringUtils.isEmpty(authCode)){
                return fail("","验证码不能为空");
            }

            String temp = redisTemplate.opsForValue().get("AUTH_CODE_" + phone);
            if(StringUtils.isBlank(temp)){
                return fail("", "验证码已失效");
            }
            if (temp.equals(authCode)) {
                //生成token
               // userEntity.setPassword(null);
               // String token = JWTUtil.getTokenByUserInfo(userEntity);
                //生成token
                userEntity.setPassword(null);
                String redisToken = redisTemplate.opsForValue().get("session:"+userEntity.getInstitutionNo()+":"+userEntity.getPhone()+":"+userEntity.getRoleType());
                String token = redisToken;
                try {
                    JWTUtil.verify(token);
                }catch (Exception e){
                    e.printStackTrace();
                    token = JWTUtil.getTokenByUserInfo(userEntity);
                    redisTemplate.opsForValue().set("session:"+userEntity.getInstitutionNo()+":"+userEntity.getPhone()+":"+userEntity.getRoleType(),token,5, TimeUnit.DAYS);
                }
                // 创建返回的json对象
                JSONObject resultJson = new JSONObject();
                resultJson.put("user", userEntity);
                resultJson.put("type", userEntity.getRoleType());
                resultJson.put("token", token);
                request.getSession().setAttribute("user", userEntity);
                return success(resultJson);
            } else {
                return fail("", "验证码错误");
            }
        }catch (Exception e){
            e.printStackTrace();
            return fail();
        }
    }


    /**
     * 忘记密码
     * @param jsonParam 参数
     * @desc 局域网和公网版 区别：公网版需要验证码参数
     * @return
     */
    @SafetyProcess
    @ApiOperation(value = "忘记密码",notes = "json字符串形式传参（加密）,data参数包括:password:新密码,institutionNo:机构编号,phone:账号或电话,roleType:用户角色,authCode:验证码（公网版必填），" +
            "verification:验证信息《beginTime:时间,authCode:验证码,phone:电话》")
    @PostMapping("/forgotPassword")
    public Result forgotPassword(@RequestBody String jsonParam){
        try {
            JSONObject dataParam = JSONObject.parseObject(AesEncryptUtils.decrypt(JSONObject.parseObject(jsonParam).getString("data")));
            String phone = dataParam.getString("phone");
            String password = dataParam.getString("password");
            String institutionNo = dataParam.getString("institutionNo");
            String roleType = dataParam.getString("roleType");
            if ( StringUtils.isEmpty( phone)  || StringUtils.isEmpty( password )  || StringUtils.isEmpty( institutionNo ) ) {
                return fail("", "请按要求填写所需信息");
            }
            UserEntity userEntity = this.userService.findPhoneAndInstitutionNoAndRoleType(phone,institutionNo,roleType);
            if (userEntity == null) {
                return fail("", "请先注册");
            }
            userEntity.setPassword(password);
            //区分公网版和非公网版
            if (Constant.WEB_INSTITUTION_CODE.equals(institutionNo)){
                String authCode = dataParam.getString("authCode");
                JSONObject jsonVerification = dataParam.getJSONObject("verification");
                String jsonPhone = jsonVerification.getString("phone");
                String jsonAuthCode = jsonVerification.getString("authCode");
                String jsonBeginTime = jsonVerification.getString("beginTime");
                if (StringUtils.isEmpty(jsonBeginTime ) || StringUtils.isEmpty(jsonAuthCode) ) {
                    return fail("", "请重新获取验证码");
                }
                //计算时间差---分钟
                //int diff = DateUtil.getDistanceByUnit(DateUtil.parseDate(jsonBeginTime), DateUtil.getCurrentDate(), 2);
                long diff = DateUtil.between(DateUtil.date(), DateUtil.parse(jsonBeginTime,PURE_DATETIME_PATTERN), DateUnit.MINUTE);
                if (diff < 0 || diff > 5) {
                    return fail("", "验证码已失效");
                }
                if (jsonAuthCode.equals(authCode) && jsonPhone.equals(phone)) {
                   // this.userService.updatePassword(phone, password, institutionNo,roleType);
                    this.userService.save(userEntity);
                } else {
                    return fail("", "验证码错误");
                }
            }else {
                this.userService.save(userEntity);
               // this.userService.updatePassword(phone, password, institutionNo,roleType);
            }
            return success();
        }catch (Exception e){
            e.printStackTrace();
            return fail();
        }
    }

    /**
     * 登出
     * @param jsonParam 参数
     * @desc
     * @return
     */
    @SafetyProcess
    @ApiOperation(value = "登出",notes = "json字符串形式传参（加密）,data参数包括:institutionNo:机构编号,phone:账号或电话,roleType:用户角色" )
    @PostMapping("/logout")
    public Result logout(@RequestBody String jsonParam){
        try {
            JSONObject dataParam = JSONObject.parseObject(AesEncryptUtils.decrypt(JSONObject.parseObject(jsonParam).getString("data")));
            String phone = dataParam.getString("phone");
            String institutionNo = dataParam.getString("institutionNo");
            String roleType = dataParam.getString("roleType");
            if ( StringUtils.isEmpty( phone)   || StringUtils.isEmpty( institutionNo ) ) {
                return fail("", "请按要求填写所需信息");
            }
            //首先校验用户是否存在
            UserEntity userEntity = userService.findPhoneAndInstitutionNoAndRoleType(phone,institutionNo,roleType);
            if (userEntity == null){
                return fail(null,"用户不存在");
            }
            if ("lan".equals(profileValue)){
                return success();
            }
            boolean result = redisTemplate.delete("session:"+institutionNo+":"+phone+":"+roleType);
            return success(result);
        }catch (Exception e){
            e.printStackTrace();
            return fail();
        }
    }

    /**
     * 修改密码
     * @param jsonParam 待修改用户密码参数
     * @return
     */
    @SafetyProcess
    @ApiOperation(value = "修改密码",notes = "data参数包括：id:用户id,password:新密码,oldPassword:旧密码")
    @PostMapping("/updatePassword")
    public Result updatePassword(@RequestBody String jsonParam){
        try {
            JSONObject jsonObject = JSONObject.parseObject(AesEncryptUtils.decrypt(JSONObject.parseObject(jsonParam).getString("data")));
            if(!jsonObject.containsKey("id")|| StringUtils.isEmpty(jsonObject.getString("id"))) {
                return failBadRequest(null,"用户id不能为空！");
            }
            if(!jsonObject.containsKey("password")|| StringUtils.isEmpty(jsonObject.getString("password"))) {
                return failBadRequest(null,"登录密码不能为空！");
            }
            String password =  jsonObject.getString("password");
            String oldPassword = jsonObject.getString("oldPassword");
            String id = jsonObject.getString("id");
            UserEntity userEntity = userService.findOne(id);
            if (userEntity == null) {
                return fail("", "请先注册");
            }
            if (!userEntity.getPassword().equals(oldPassword)) {
                return fail("", "旧密码有误");
            }
            userEntity.setPassword(password);
            this.userService.save(userEntity);
            return success();
        }catch (Exception e){
            e.printStackTrace();
            return fail();
        }
    }


    @ApiOperation(value = "量表加密操作")
    @GetMapping("/update/{flag}")
    public String update(@PathVariable String flag){

        //根据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);



        for (SubjectEntity subjectEntity:subjectEntities){
            //String description = DESede.encryptString(subjectEntity.getDescription());
            subjectEntity.setDescription(DESede.encryptString(subjectEntity.getDescription()));
            this.subjectService.update(subjectEntity);
        }

        for (AnswerEntity answerEntity:answerEntities){
            answerEntity.setName(DESede.encryptString(answerEntity.getName()));
            answerEntity.setScore(DESede.encryptString(answerEntity.getScore()));
            this.answerService.updateAnswer(answerEntity);

        }
        for (ScaleEntity scaleEntity:scaleEntities){
            scaleEntity.setAnswer(DESede.encryptString(scaleEntity.getAnswer()));
            scaleEntity.setCheckItems(DESede.encryptString(scaleEntity.getCheckItems()));
            this.scaleService.updateScale(scaleEntity);

        }
        for (ScaleMarksEntity scaleMarksEntity:scaleMarksEntities){
            scaleMarksEntity.setName(DESede.encryptString(scaleMarksEntity.getName()));
            scaleMarksEntity.setScoreStart(DESede.encryptString(scaleMarksEntity.getScoreStart()));
            scaleMarksEntity.setScoreEnd(DESede.encryptString(scaleMarksEntity.getScoreEnd()));
            scaleMarksEntity.setSymptom(DESede.encryptString(scaleMarksEntity.getSymptom()));
            scaleMarksEntity.setImprovementSuggestions(DESede.encryptString(scaleMarksEntity.getImprovementSuggestions()));
            scaleMarksEntity.setNameExplain(DESede.encryptString(scaleMarksEntity.getImprovementSuggestions()));
            scaleMarksEntity.setReference(DESede.encryptString(scaleMarksEntity.getImprovementSuggestions()));
            scaleMarksEntity.setSuggestion(DESede.encryptString(scaleMarksEntity.getImprovementSuggestions()));
            scaleMarksEntity.setStandardDeviation(DESede.encryptString(scaleMarksEntity.getImprovementSuggestions()));
            this.scaleMarksService.updateMark(scaleMarksEntity);

        }
        for (DimensionEntity dimensionEntity:dimensionEntities){
            dimensionEntity.setName(DESede.encryptString(dimensionEntity.getName()));
            dimensionEntity.setQuestionNo(DESede.encryptString(dimensionEntity.getQuestionNo()));
            this.dimensionService.updateDimension(dimensionEntity);

        }

        System.out.println("hello");
        return "hello";
    }



}
