package com.rf.psychological.rest;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rf.psychological.base.rest.BaseController;
import com.rf.psychological.dao.dto.*;
import com.rf.psychological.dao.model.*;
import com.rf.psychological.enums.UserRole;
import com.rf.psychological.enums.UserStatus;
import com.rf.psychological.group.dao.model.GroupAuthEntity;
import com.rf.psychological.group.dao.model.GroupEntity;
import com.rf.psychological.group.service.GroupAuthService;
import com.rf.psychological.group.service.GroupInfoService;
import com.rf.psychological.institution.model.InstitutionAuthEntity;
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.service.TestPlanContendService;
import com.rf.psychological.scale.dao.dto.SubjectEntityDto2;
import com.rf.psychological.scale.dao.model.*;
import com.rf.psychological.scale.service.*;
import com.rf.psychological.security.SafetyProcess;
import com.rf.psychological.socket.MyClient;
import com.rf.psychological.user.dao.model.UserEntity;
import com.rf.psychological.user.dao.model.UserFileEntity;
import com.rf.psychological.user.service.UserFileService;
import com.rf.psychological.user.service.UserService;
import com.rf.psychological.utils.*;
import com.rf.psychological.wxpay.model.PromotionInfo;
import com.rf.psychological.wxpay.service.OrderInfoService;
import com.rf.psychological.wxpay.service.PromotionInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @author zzf
 * @description:扫描服务器时进行验证
 * @date 2021/5/11 17:24
 */
@Slf4j
@Api(tags = "量表操作-detail")
@RestController
public class ServerController extends BaseController {

    /**
     * 任务执行状态 0-->未开始；1-->进行中；2-->已结束
     **/
    public static Map<String,String> TASK_STATUS = new HashMap<>();

    @Autowired
    private ScaleService scaleService;
    @Autowired
    private UserService userService;
    @Autowired
    private SubjectService subjectService;

    @Autowired
    private UserRecordService userRecordService;

    @Autowired
    private AnswerService answerService;

    @Autowired
    private ScaleMarksService scaleMarksService;

    @Autowired
    private CognitiveTaskService cognitiveTaskService;

    @Autowired
    private InstitutionAuthService institutionAuthService;

    @Autowired
    private CategorySubjectService categorySubjectService;

    @Autowired
    private DimensionService dimensionService;

    @Autowired
    private TestPlanContendService testPlanContendService;

    @Autowired
    private GroupAuthService groupAuthService;

    @Autowired
    private GroupInfoService groupInfoService;

    @Autowired
    private InstitutionService institutionService;

    @Autowired(required = false)
    private OrderInfoService orderInfoService;

    @Autowired
    private UserFileService userFileService;

    @Autowired
    private ScaleDetailsService scaleDetailsService;


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

    @Autowired
    private PromotionInfoService promotionInfoService;
    @SafetyProcess
    @GetMapping("server")
    public Result scanServer() {
        return success("", "psychological");
    }

    /**
     * 导入量表
     * 1、量表名称  2、量表指导语  3、量表录入人
     *
     * @return
     */
    //@SafetyProcess
    @PostMapping("import")
    @ApiOperation(value = "量表导入")
    public Result importScale(String scaleName, String scaleDesc, String uploader, String eName, String scoringPrinciple, MultipartFile file) throws Exception {
        if (file == null) {
            return fail("文件为空");
        }
        String message = "提交成功";
        //保存基本信息
        //量表标志自动生成唯一值，yyyyMMddHHmmss
        String flag = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());

        SubjectEntity subjectEntity = new SubjectEntity();
        subjectEntity.setName(scaleName);
        subjectEntity.setFlag(flag);
        //类型默认量表
        subjectEntity.setType("0");
//        新增量表默认为热门测试
        subjectEntity.setIsHot("1");
//        新增量表默认为最新测试
        subjectEntity.setIsNew(1);
        subjectEntity.setDescription(scaleDesc);
        subjectEntity.setUploader(uploader);
        subjectEntity.setEName(eName);
        subjectEntity.setScoringPrinciple(scoringPrinciple);
        if (subjectEntity.getName() == null || subjectEntity.getName().trim().length() == 0) {
            return fail(null, "量表名称为空");
        }
        if (subjectEntity.getUploader() == null || subjectEntity.getUploader().trim().length() <= 0) {
            return fail(null, "请输入上传人信息");
        }

        List<List<Object>> datas = ExcelUtil.getBankListByExcel(file.getInputStream(), file.getOriginalFilename());

        for (int i = 0; i < datas.size(); i++) {
            List<Object> scales = datas.get(i);
            System.out.println(scales);
            ScaleEntity scaleEntity = new ScaleEntity();
            scaleEntity.setQuestionNo(scales.get(0).toString());
            scaleEntity.setSerialNo(scales.get(1).toString());
            scaleEntity.setAnswer(scales.get(2).toString());
            scaleEntity.setCheckItems(scales.get(3).toString());
            //类型：0-单选 1-多选 2-填空
            String questionType = scales.get(4).toString();
            if (questionType.equals("多选")) {
                scaleEntity.setQuestionType(Constant.MAGIC_NUM_1);
            } else if (questionType.equals("填空")) {
                scaleEntity.setQuestionType(Constant.MAGIC_NUM_2);
            } else {
                scaleEntity.setQuestionType(Constant.MAGIC_NUM_0);
            }
            scaleEntity.setWeight("");
            String scoreDirection = scales.get(5).toString();
            if (scoreDirection.equals("正向")) {
                scoreDirection = Constant.MAGIC_NUM_1;
            } else if (scoreDirection.equals("反向")) {
                scoreDirection = Constant.MAGIC_NUM_MINUS_1;
            }
            scaleEntity.setScoreDirection(scoreDirection);
//            量表模板不提供分值
            scaleEntity.setScore("");
            scaleEntity.setFlag(flag);
            this.scaleService.saveScale(scaleEntity);
        }
        //文件保存
        String fileName;
        String FILEDIR;

        if (OSUtil.getOSname().equalsIgnoreCase("Windows")) {
            FILEDIR = "./psychological/scales/";
        } else {
            FILEDIR = "./scales/";
        }
        String suffix = file.getOriginalFilename();

        if (!file.isEmpty()) {
            fileName = suffix;
            subjectEntity.setFileName(fileName);
            try {
                File temp = new File(FILEDIR);
                if (!temp.exists()) {
                    temp.mkdirs();
                }
                File fileLocal = new File(FILEDIR, fileName);
                FileUtils.copyInputStreamToFile(file.getInputStream(), fileLocal);
            } catch (Exception e) {
                message = message + "文件上传失败";
                e.printStackTrace();
                return fail(message);
            }
        }
        this.subjectService.save(subjectEntity);
        return success();
    }

    /**
     * 查询列表
     *
     * @return
     */
    @GetMapping("subjectInfo")
    @ApiOperation(value = "量表全量查询，包含认知任务")
    public Result getScaleList(int pageNum, int pageSize, String searchName) {
        List<SubjectEntity> subjectEntityList = new ArrayList<>();
        int num = 0;
        if (pageSize == 0) {
            pageSize = 20;
        }
        System.out.println("searchName-----" + searchName);
        if (searchName == null || searchName.equals("")) {
            subjectEntityList = this.subjectService.findAll(pageNum, pageSize);
            num = this.subjectService.allNum();
        } else {
            try {
                subjectEntityList = this.subjectService.findByNameOrUploader(pageNum, pageSize, searchName);
                num = this.subjectService.allNumByNameOrUploader(searchName);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        List<SubjectEntityDto> dto = new ArrayList<>();
        for (SubjectEntity subjectEntity : subjectEntityList) {
            SubjectEntityDto subjectEntityDto = new SubjectEntityDto(subjectEntity);
            //--add  by zzf 量表查询新增价格字段  key=price---
            PromotionInfo infoBySubjectId = promotionInfoService.findInfoBySubjectId(subjectEntity.getId());
            subjectEntityDto.setPrice(infoBySubjectId == null ? 0.0 : infoBySubjectId.getPrice());
            //-----end-----
            List<CategorySubjectEntity> categorySubjectEntityList = this.categorySubjectService.findByFlag(subjectEntity.getFlag());
            if (categorySubjectEntityList != null && categorySubjectEntityList.size() > 0) {
                subjectEntityDto.setCategory(categorySubjectEntityList);
            } else {
                subjectEntityDto.setCategory(null);
            }
            dto.add(subjectEntityDto);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data", dto);
        jsonObject.put("allNum", num);
        return success(jsonObject);
    }

    /**
     * 量表上传多条件查询列表
     *
     * @return
     */
    @PostMapping("subjectInfoList")
    @ApiOperation(value = "量表多条件全量查询")
    public Result getScales(@RequestBody JSONObject jsonObject) {
        /*
        * 量表名称、量表分类、适用人群、量表权限
        * */
        String name = null;
        if (jsonObject.containsKey("name")) {
            name = jsonObject.getString("name");
        }
        String scaleCate = null;
        if (jsonObject.containsKey("scaleCate")) {
            scaleCate = jsonObject.getString("scaleCate");
        }
        String people = null;
        if (jsonObject.containsKey("people")) {
            people = jsonObject.getString("people");
        }
        String currentLimit = null;
        if (jsonObject.containsKey("currentLimit")) {
            currentLimit = jsonObject.getString("currentLimit");
        }
        int pageNum =  jsonObject.getInteger("pageNum");
        int pageSize =  jsonObject.getInteger("pageSize");
        if (pageSize == 0) {
            pageSize = 20;
        }
        List<SubjectEntity> subjectEntityList = new ArrayList<>();
        Page<SubjectEntity> subjectEntitys = this.subjectService.getsubjectListMultiCondition(name, scaleCate, people, currentLimit, pageNum, pageSize);
        subjectEntityList = subjectEntitys.getContent();
        List<SubjectEntityDto> dto = new ArrayList<>();
        for (SubjectEntity subjectEntity : subjectEntityList) {
            SubjectEntityDto subjectEntityDto = new SubjectEntityDto(subjectEntity);
            List<CategorySubjectEntity> categorySubjectEntityList = this.categorySubjectService.findByFlag(subjectEntity.getFlag());
            if (categorySubjectEntityList != null && categorySubjectEntityList.size() > 0) {
                subjectEntityDto.setCategory(categorySubjectEntityList);
            } else {
                subjectEntityDto.setCategory(null);
            }
            dto.add(subjectEntityDto);
        }
        JSONObject json = new JSONObject();
        json.put("data", dto);
        json.put("allNum", subjectEntitys.getTotalElements());
        return success(json);
    }

    /**
     * 查询机构自定义量表列表
     *
     * @return
     */
    @GetMapping("subjectInfo/institutionByTC")
    @ApiOperation(value = "查询机构自定义量表列表")
    public Result getInstitutionByTC(int pageNum, int pageSize, String institutionNo) {
        List<SubjectEntity> subjectEntityList;
        int num = 0;
        if (pageSize == 0) {
            pageSize = 20;
        }
        subjectEntityList = this.subjectService.institutionByTC(pageNum, pageSize, institutionNo);
        num = this.subjectService.institutionByTCNum(institutionNo);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data", subjectEntityList);
        jsonObject.put("allNum", num);
        System.out.println(subjectEntityList);
        return success(jsonObject);
    }

    /**
     * 征冰心理健康测评消息推送
     *
     * @return
     */
    @GetMapping("push/message/{phone}")
    @ApiOperation(value = "心理健康测评消息推送")
    public Result pushMessage(@PathVariable String phone) throws InterruptedException {
        String url = "ws://127.0.0.1:54378/ws";
        MyClient myClient = new MyClient(url);
        myClient.connectBlocking();
        JSONObject dataJson = new JSONObject();
        dataJson.put("flag","begin");
        dataJson.put("date", LocalDateTime.now().toString());
        myClient.send(dataJson.toString());
        Thread.sleep(500);
        myClient.close();
        this.TASK_STATUS.put(phone,"1");
        return success();
    }

    /**
     * 征冰心理健康测评状态查询
     *
     * @return
     */
    @GetMapping("push/status/{phoneNumber}")
    @ApiOperation(value = "征冰心理健康测评状态查询")
    public Result pushStatus(@PathVariable String phoneNumber) {
        return success(this.TASK_STATUS.get(phoneNumber) == null?"0":this.TASK_STATUS.get(phoneNumber));
    }

    /**
     * 用户查询靶向神经振荡评估与训练记录
     *
     * @return
     */
    @SafetyProcess
    @GetMapping("RHYTHM/{phone}/{institutionNo}/{testPlanId}")
    @ApiOperation(value = "用户查询靶向神经振荡评估与训练记录")
    public Result RHYTHM(@PathVariable String phone, @PathVariable String institutionNo, @PathVariable String testPlanId) {
        UserRecordEntity userRecordEntity = this.userRecordService.getRHYTHM(phone, institutionNo, testPlanId);
        if (userRecordEntity != null && userRecordEntity.getImg() != null) {
            return success(userRecordEntity.getImg());
        }
        return success("");
    }

    /**
     * 删除机构自定义量表
     *
     * @return
     */
    @GetMapping("subjectInfo/delete")
    public Result deleteSubjectInfo(String flag) {
        //删除量表分类关联信息
        this.categorySubjectService.deleteCategorySubjectByFlag(flag);
        //删除量表权限关联信息
        this.institutionAuthService.deleteInstitutionByFlag(flag);
        //删除量表分组信息
        this.groupAuthService.deleteGroupByFlag(flag);
        //删除量表测试计划信息
        this.testPlanContendService.deleteTestPlanByFlag(flag);
        //删除量表计分规则信息
        this.answerService.deleteAnswerByFlag(flag);
        //删除量表判断标准信息
        this.scaleMarksService.deleteScaleMarkByFlag(flag);
        //删除量表维度信息
        this.dimensionService.deleteDimensionByFlag(flag);
        //删除量表题目信息
        this.scaleService.deleteScaleByFlag(flag);
        //删除量表基本信息
        this.subjectService.deleteSubjectByFlag(flag);

        return success();
    }

    @PostMapping("subjectInfo/update")
    public Result updateSubjectInfo(@RequestBody JSONObject jsonObject) {
        JSONArray categoryList = jsonObject.getJSONArray("type");
        String flag = jsonObject.getString("flag");
        String scaleLimit = jsonObject.getString("scaleLimit");
        /*String  men = jsonObject.getString("people");
        men = men.replace("[","").replace("]","");
        if(men.contains("0")){
            men = "0";
        }*/
        this.categorySubjectService.deleteCategorySubjectByFlag(flag);
        for (Object obj : categoryList) {
            CategorySubjectEntity categorySubjectEntity = new CategorySubjectEntity();
            categorySubjectEntity.setFlag(flag);
            categorySubjectEntity.setEname((String) obj);
            this.categorySubjectService.save(categorySubjectEntity);
        }
        SubjectEntity subjectEntity = this.subjectService.getSubjectEntityByFlag(flag);
        if (subjectEntity != null) {
            subjectEntity.setScaleLimit(scaleLimit);
            //subjectEntity.setMen(men.replace(" ",""));
            this.subjectService.save(subjectEntity);
        }
        return success();
    }

    /**
     * 量表上传需要接口
     *
     * @return
     */
    @PostMapping("subjectInfoUpload/update")
    public Result updateSubjectInfoUpload(@RequestBody JSONObject jsonObject) {
        JSONArray categoryList = jsonObject.getJSONArray("type");
        String flag = jsonObject.getString("flag");
        String scaleLimit = jsonObject.getString("scaleLimit");
        String  men = jsonObject.getString("people");
        men = men.replace("[","").replace("]","");
        if(men.contains("0")){
            men = "0";
        }
        this.categorySubjectService.deleteCategorySubjectByFlag(flag);
        for (Object obj : categoryList) {
            CategorySubjectEntity categorySubjectEntity = new CategorySubjectEntity();
            categorySubjectEntity.setFlag(flag);
            categorySubjectEntity.setEname((String) obj);
            this.categorySubjectService.save(categorySubjectEntity);
        }
        SubjectEntity subjectEntity = this.subjectService.getSubjectEntityByFlag(flag);
        if (subjectEntity != null) {
            subjectEntity.setScaleLimit(scaleLimit);
            subjectEntity.setMen(men.replace(" ",""));
            this.subjectService.save(subjectEntity);
        }
        return success();
    }

    /**
     * 查询列表
     *
     * @return
     */
    @SafetyProcess
    @ApiOperation(value = "量表查询，type=0 量表。type=1 认知任务")
    @GetMapping("subjectInfo/{type}")
    public Result getScaleListByType(@PathVariable String type) {
        List<SubjectEntity> subjectEntityList = this.subjectService.findAll(type);
        return success(subjectEntityList);
    }

    /**
     * 保存量表
     *
     * @param subjectEntity
     * @return
     */

    @PostMapping("save/scale")
    @ApiOperation("增加量表")
    public Result saveScaleInfo(SubjectEntity subjectEntity) {
        System.out.println(subjectEntity);
        if (subjectEntity.getType() == null || subjectEntity.getType().trim().length() <= 0) {
            subjectEntity.setType("0");
        }
        if (subjectEntity.getIsHot() == null || subjectEntity.getIsHot().trim().length() <= 0) {
            subjectEntity.setIsHot("1");
        }
        if (subjectEntity.getIsNew() != 0) {
            subjectEntity.setIsNew(1);
        }
        if (subjectEntity.getName() == null || subjectEntity.getName().trim().length() == 0) {
            return fail(null, "量表名称为空");
        }
        if (subjectEntity.getUploader() == null || subjectEntity.getUploader().trim().length() <= 0) {
            return fail(null, "请输入上传人信息");
        }
        this.subjectService.save(subjectEntity);
        return success();
    }


    /**
     * getSubjectListByAuth
     * 根据名称模糊查询量表列表
     *
     * @return
     */
    @SafetyProcess
    @GetMapping("subjectInfo/getSubjectListByName")
    @ApiOperation(value = "根据名称模糊查询量表列表")
    public Result getSubjectListByName(int pageNum, int pageSize, String scaleName, String categoryEname) {
        if (pageSize == 0) {
            pageSize = 20;
        }
        int num;
        List<SubjectEntity> subjectEntityList;
        if (categoryEname.equals("ALL")) {
            if (StringUtils.isEmpty(scaleName)) {
                subjectEntityList = this.subjectService.findAll(pageNum, pageSize);
                num = this.subjectService.allNum();
            } else {
                subjectEntityList = this.subjectService.getSubjectListByName(pageNum, pageSize, scaleName);
                num = this.subjectService.allNumByName(scaleName);
            }
        } else {
            if (StringUtils.isEmpty(scaleName)) {
                subjectEntityList = this.subjectService.findAllCategory(pageNum, pageSize, categoryEname);
                num = this.subjectService.allNumCategory(categoryEname);
            } else {
                subjectEntityList = this.subjectService.getSubjectListByNameCategory(pageNum, pageSize, scaleName, categoryEname);
                num = this.subjectService.allNumByNameCategory(scaleName, categoryEname);
            }
        }
        List<SubjectEntityDto2> dto2List = new ArrayList<>();
        if(num>0){
            subjectEntityList.forEach(subjectEntity -> {
                SubjectEntityDto2 dto = new SubjectEntityDto2(subjectEntity);
                PromotionInfo infoBySubjectId = promotionInfoService.findInfoBySubjectId(subjectEntity.getId());
                dto.setPrice( infoBySubjectId ==null?0.0:infoBySubjectId.getPrice());
                dto2List.add(dto);
            });
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data", dto2List);
        jsonObject.put("allNum", num);
        return success(jsonObject);
    }

    /**
     * 根据名称模糊查询认知任务列表
     *
     * @return
     */
    @SafetyProcess
    @GetMapping("subjectInfo/getCognizeListByName")
    @ApiOperation(value = "根据名称模糊查询认知任务列表")
    public Result getCognizeListByName(int pageNum, int pageSize, String scaleName, String categoryEname) {
        if (pageSize == 0) {
            pageSize = 20;
        }
        int num;
        List<CognitiveTaskEntity> cognitiveTaskEntityList;
        if (categoryEname.equals("CALL")) {
            if (StringUtils.isEmpty(scaleName)) {
                cognitiveTaskEntityList = this.cognitiveTaskService.findAll(pageNum, pageSize);
                num = this.cognitiveTaskService.allNum();
            } else {
                cognitiveTaskEntityList = this.cognitiveTaskService.getCognizeListByName(pageNum, pageSize, scaleName);
                num = this.cognitiveTaskService.allNumByName(scaleName);
            }
        } else {
            if (StringUtils.isEmpty(scaleName)) {
                cognitiveTaskEntityList = this.cognitiveTaskService.findAllCategory(pageNum, pageSize, categoryEname);
                num = this.cognitiveTaskService.allNumCategory(categoryEname);
            } else {
                cognitiveTaskEntityList = this.cognitiveTaskService.getCognizeListByNameCategory(pageNum, pageSize, scaleName, categoryEname);
                num = this.cognitiveTaskService.allNumByNameCategory(scaleName, categoryEname);
            }
        }
        //------add by zzf begin  认知任务列表查询，新增价格字段 key=price----
        List<CognitiveTaskEntityDto> dto2List = new ArrayList<>();
        if(num>0){
            cognitiveTaskEntityList.forEach(cognitiveTaskEntity -> {
                CognitiveTaskEntityDto dto = new CognitiveTaskEntityDto(cognitiveTaskEntity);
                PromotionInfo infoBySubjectId = promotionInfoService.findInfoBySubjectId(cognitiveTaskEntity.getId());
                dto.setPrice( infoBySubjectId ==null?0.0:infoBySubjectId.getPrice());
                dto2List.add(dto);
            });
        }
        //----end----
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data", dto2List);
        jsonObject.put("allNum", num);
        return success(jsonObject);
    }


    /**
     * 根据权限，查看用户的认知任务权限
     *
     * @return
     */
    @SafetyProcess
    @GetMapping("subjectInfo/getCognizeListByAuth")
    @ApiOperation(value = "根据名称模糊查询认知任务列表")
    public Result getCognizeListByAuth(int pageNum, int pageSize, String scaleName, String categoryEname, String uId, String institutionNo,
                                       @RequestParam(value = "mobile", defaultValue = "false") Boolean mobile) {
        if (pageSize == 0) {
            pageSize = 20;
        }
        //游客用户无id，数据库配置特定用户
        if (StringUtils.isEmpty(uId)){
            uId = Constant.PUBLIC_VISITOR_ID;
        }
        int num;
        List<CognitiveTaskEntity> cognitiveTaskEntityList = new ArrayList<>();
        UserEntity one = userService.getOne(uId);
        System.out.println(one);
        if (("0").equals(one.getGId())) {
            if (categoryEname.equals("CALL")) {
                List<InstitutionAuthConTaskDto> allConTask = this.institutionAuthService.getAllConTask(pageNum, pageSize, institutionNo, "1", scaleName, mobile);
                for (InstitutionAuthConTaskDto institutionAuthConTaskDto : allConTask) {
                    CognitiveTaskEntity cognitiveTaskEntity = new CognitiveTaskEntity();
                    BeanUtils.copyProperties(institutionAuthConTaskDto, cognitiveTaskEntity);
                    cognitiveTaskEntityList.add(cognitiveTaskEntity);
                }
                num = this.institutionAuthService.getAllConTaskNum(institutionNo, "1", scaleName, mobile);
            } else {
                Page<CognitiveTaskEntity> institutionTaskAuthAndCateEName = this.cognitiveTaskService.findInstitutionTaskAuthAndCateEName(institutionNo, scaleName, categoryEname, pageNum, pageSize, mobile);
                cognitiveTaskEntityList = institutionTaskAuthAndCateEName.getContent();
                num = (int) institutionTaskAuthAndCateEName.getTotalElements();
            }
        } else {
            if (categoryEname.equals("CALL")) {
                Page<CognitiveTaskEntity> userTaskAuth = this.cognitiveTaskService.findUserTaskAuth(uId, scaleName, pageNum, pageSize, mobile);
                cognitiveTaskEntityList = userTaskAuth.getContent();
                num = (int) userTaskAuth.getTotalElements();
            } else {
                Page<CognitiveTaskEntity> userTaskAuth = this.cognitiveTaskService.findUserTaskAuthAndCateEName(uId, scaleName, categoryEname, pageNum, pageSize, mobile);
                cognitiveTaskEntityList = userTaskAuth.getContent();
                num = (int) userTaskAuth.getTotalElements();
            }
        }
        //----add by zzf begin 认知任务查询新增price  key=price---
        List<CognitiveTaskEntityDto> dto2List = new ArrayList<>();
        if(num>0){
            cognitiveTaskEntityList.forEach(cognitiveTaskEntity -> {
                CognitiveTaskEntityDto dto = new CognitiveTaskEntityDto(cognitiveTaskEntity);
                PromotionInfo infoBySubjectId = promotionInfoService.findInfoBySubjectId(cognitiveTaskEntity.getId());
                dto.setPrice( infoBySubjectId ==null?0.0:infoBySubjectId.getPrice());
                dto2List.add(dto);
            });
        }
        //---end ----
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data", dto2List);
        jsonObject.put("allNum", num);
        return success(jsonObject);
    }

    /**
     * 根据用户的分组权限
     * 查看用户的量表权限
     * 用户分组为0时查询机构权限
     * 用户分组不为0时查询自己分组下的权限
     *
     * @return
     */
    @SafetyProcess
    @GetMapping("subjectInfo/getSubjectListByAuth")
    @ApiOperation(value = "根据权限名称模糊查询量表列表")
    public Result getSubjectListByAuth(int pageNum, int pageSize, String scaleName, String categoryEname, String institutionNo, String uId, HttpSession session) {
        if (pageSize == 0) {
            pageSize = 20;
        }
        //游客用户无id，数据库配置特定用户
        if (StringUtils.isEmpty(uId)){
            uId = Constant.PUBLIC_VISITOR_ID;
        }
        long num;
        List<SubjectEntity> subjectEntityList = new ArrayList<>();
        UserEntity one = userService.getOne(uId);
        if (("0").equals(one.getGId())) {
            if (categoryEname.equals("ALL")) {
                List<InstitutionAuthSubjectNameDto> byInstitutionNoAndName = this.institutionAuthService.getByInstitutionNoAndName(pageNum, pageSize, institutionNo, "0", scaleName,null);
                for (InstitutionAuthSubjectNameDto institutionAuthSubject : byInstitutionNoAndName) {
                    SubjectEntity subjectEntity = new SubjectEntity();
                    BeanUtils.copyProperties(institutionAuthSubject, subjectEntity);
                    subjectEntity.setEName(institutionAuthSubject.getEname());
                    subjectEntityList.add(subjectEntity);
                }
                num = this.institutionAuthService.getAllByTableInAuthAndSubInfoNum(institutionNo, "0", scaleName,null);
            } else {
                subjectEntityList = this.subjectService.getSubjectListByAuthAndCategory(pageNum, pageSize, scaleName, categoryEname, institutionNo);
                num = this.subjectService.allNumByAuth(scaleName, categoryEname, institutionNo);
            }
        } else {
            if (categoryEname.equals("ALL")) {
                Page<SubjectEntity> userAuth = userService.findUserAuth(uId, pageNum, pageSize, scaleName);
//            subjectEntityList = this.subjectService.getSubjectListByAuth(pageNum, pageSize, scaleName, institutionNo);
//            System.out.println(subjectEntityList.size());
//            num = this.subjectService.allNumByAuth(scaleName, "", institutionNo);
                subjectEntityList = userAuth.getContent();
                num = userAuth.getTotalElements();
            } else {
//            subjectEntityList = this.subjectService.getSubjectListByAuthAndCategory(pageNum, pageSize, scaleName, categoryEname, institutionNo);
//            num = (long) this.subjectService.allNumByAuth(scaleName, categoryEname, institutionNo);
                Page<SubjectEntity> userAuthAndCateEName = this.subjectService.findUserAuthAndCateEName(uId, scaleName, categoryEname, pageNum, pageSize);
                subjectEntityList = userAuthAndCateEName.getContent();
                num = userAuthAndCateEName.getTotalElements();
            }
        }
        //----add by zzf  begin 量表查询新增价格 key=price----
        List<SubjectEntityDto2> dto2List = new ArrayList<>();
        if(num>0){
            subjectEntityList.forEach(subjectEntity -> {
                SubjectEntityDto2 dto = new SubjectEntityDto2(subjectEntity);
                PromotionInfo infoBySubjectId = promotionInfoService.findInfoBySubjectId(subjectEntity.getId());
                dto.setPrice( infoBySubjectId ==null?0.0:infoBySubjectId.getPrice());
                List<ScaleEntity> scaleEntityList = this.scaleService.getScaleByFlag(subjectEntity.getFlag());
                dto.setTitleNum(scaleEntityList.size());
                dto2List.add(dto);
            });
        }
        //-----end------
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data", dto2List);
        jsonObject.put("allNum", num);
        return success(jsonObject);
    }

    /**
     * 量表和认知任务热搜榜
     *
     * @return
     */
    @SafetyProcess
    @GetMapping("subjectInfo/getTrendingSearches")
    @ApiOperation(value = "量表和认知任务热搜榜",notes = " type:类型0量表1认知任务")
    public Result getTrendingSearches(String type) {
        Set<Integer> set = new HashSet<>(); // 创建Set集合保存随机数
        Random random = new Random(); // 创建Random对象生成随机数
        while (set.size() < 6) { // 生成6个不重复随机数
            int num = random.nextInt(10) + 1; // 生成1到32之间的随机数
            set.add(num); // 将随机数添加到Set集合中
        }
        if (type.equals(Constant.DEFAULT_VALUE_ZERO)) {
            List<SubjectEntity> subjectEntities = this.subjectService.getTrendingSearches(Constant.NUMBER_FIFTEEN);
            int y = 0;
            for (int i = 0; i < subjectEntities.size(); i++){
                subjectEntities.get(i).setIsNew(Integer.valueOf(Constant.DEFAULT_VALUE_ZERO));
                subjectEntities.get(i).setIsHot(Constant.DEFAULT_VALUE_ZERO);
                for (int x : set){
                    if (i == x){
                        if (y < 3){
                            subjectEntities.get(i).setIsHot(Constant.DEFAULT_VALUE_ONE);
                            set.remove(x);
                            y ++;
                            break;
                        }else if (y >= 3 && y < 6){
                            subjectEntities.get(i).setIsNew(Integer.valueOf(Constant.DEFAULT_VALUE_ONE));
                            set.remove(x);
                            y ++;
                            break;
                        }
                    }
                }
            }
            return success(subjectEntities);
        }else if (type.equals(Constant.DEFAULT_VALUE_ONE)){
            List<CognitiveTaskEntity> cognitiveTaskEntities = this.cognitiveTaskService.getTrendingSearches(Constant.NUMBER_FIVE);
            List<CognitiveTaskEntityDto> dto2List = new ArrayList<>();
            int y = 0;
            for (int i = 0; i < cognitiveTaskEntities.size(); i++){
                CognitiveTaskEntityDto dto = new CognitiveTaskEntityDto(cognitiveTaskEntities.get(i));
                for (int x : set){
                    if (i == x){
                        if (y < 3){
                            dto.setIsNew(Constant.DEFAULT_VALUE_ZERO);
                            dto.setIsHot(Constant.DEFAULT_VALUE_ONE);
                            set.remove(x);
                            y ++;
                            dto2List.add(dto);
                            break;
                        }else if (y >= 3 && y < 6){
                            dto.setIsNew(Constant.DEFAULT_VALUE_ONE);
                            dto.setIsHot(Constant.DEFAULT_VALUE_ZERO);
                            set.remove(x);
                            y ++;
                            dto2List.add(dto);
                            break;
                        }
                    }else {
                        dto.setIsNew(Constant.DEFAULT_VALUE_ZERO);
                        dto.setIsHot(Constant.DEFAULT_VALUE_ZERO);
                        dto2List.add(dto);
                        break;
                    }
                }
            }
            return success(dto2List);
        }else {
            return fail(null,"参数错误");
        }
    }

    /**
     * 根据flag查询检测列表
     *
     * @param flag
     * @return
     */
    @SafetyProcess
    @GetMapping("scaleInfo/{flag}")
    @ApiOperation("根据flag查询题目检测列表")
    public Result getScaleListByFlag(@PathVariable String flag) {
        ScaleDetailsEntity scaleDetailsEntity = scaleDetailsService.getSubjectDetailsByFlag(flag);
        if (scaleDetailsEntity == null){
            return fail("量表不存在，请联系管理员");
        }
        if (Constant.DEFAULT_VALUE_ONE.equals(scaleDetailsEntity.getIsValid())){
            return fail("无效量表，请联系管理员");
        }
        log.info("题目查询开始===================="+DateUtil.current());
        List<ScaleEntity> scaleEntityList = this.scaleService.getScaleByFlag(flag);
        log.info("题目查询结束===================="+DateUtil.current());
        return success(scaleEntityList);
    }

    /**
     * 根据flag查询
     *
     * @return
     */
    @SafetyProcess
    @ApiOperation(value = "根据flag查询")
    @GetMapping("subjectInfo/getSubjectByFlag/{flag}")
    public Result getSubjectByFlag(@PathVariable String flag) {
        List<SubjectEntity> subjectEntityList = this.subjectService.getSubjectByFlag(flag);
        List<SubjectEntityDto2> subjectEntityDto2List = new ArrayList<>();
        if(subjectEntityList != null && subjectEntityList.size()>0){
            subjectEntityList.forEach(subjectEntity -> {
                SubjectEntityDto2 subjectEntityDto2 = new SubjectEntityDto2(subjectEntity);
                PromotionInfo infoBySubjectId = this.promotionInfoService.findInfoBySubjectId(subjectEntity.getId());
                subjectEntityDto2.setPrice(infoBySubjectId == null ? 0.0:infoBySubjectId.getPrice());
                List<ScaleEntity> scaleEntityList = this.scaleService.getScaleByFlag(subjectEntity.getFlag());
                subjectEntityDto2.setTitleNum(scaleEntityList.size());
                int estimatedTime = scaleEntityList.size() / Constant.TEST_PLAN_STATUS_RUNNING + (scaleEntityList.size() % Constant.TEST_PLAN_STATUS_RUNNING != 0 ? 1 : 0);
                subjectEntityDto2.setEstimatedTime(estimatedTime);
                subjectEntityDto2List.add(subjectEntityDto2);
            });
        }
        return success(subjectEntityDto2List);
    }

    /**
     * 根据flag查询量表新版本详情
     *
     * @return
     */
    @SafetyProcess
    @ApiOperation(value = "根据flag查询量表新版本详情")
    @GetMapping("subjectInfo/getSubjectByFlagV2/{flag}")
    public Result getSubjectByFlagV2(@PathVariable String flag) {
        try {
            List<SubjectEntity> subjectEntityList = this.subjectService.getSubjectByFlag(flag);
            List<SubjectEntityDto2> subjectEntityDto2List = new ArrayList<>();
            if(subjectEntityList != null && subjectEntityList.size()>0){
                subjectEntityList.forEach(subjectEntity -> {
                    SubjectEntityDto2 subjectEntityDto2 = new SubjectEntityDto2(subjectEntity);
                    PromotionInfo infoBySubjectId = this.promotionInfoService.findInfoBySubjectId(subjectEntity.getId());
                    subjectEntityDto2.setPrice(infoBySubjectId == null ? 0.0:infoBySubjectId.getPrice());
                    List<ScaleEntity> scaleEntityList = this.scaleService.getScaleByFlag(subjectEntity.getFlag());
                    subjectEntityDto2.setTitleNum(scaleEntityList.size());
                    int estimatedTime = scaleEntityList.size() / Constant.TEST_PLAN_STATUS_RUNNING + (scaleEntityList.size() % Constant.TEST_PLAN_STATUS_RUNNING != 0 ? 1 : 0);
                    subjectEntityDto2.setEstimatedTime(estimatedTime);
                    subjectEntityDto2List.add(subjectEntityDto2);
                });
            }
            ScaleDetailsEntity scaleDetailsEntity = this.scaleDetailsService.getSubjectDetailsByFlag(flag);
            if (CollectionUtils.isEmpty(subjectEntityList)){
                return fail("量表信息不存在,请联系管理员！");
            }
            if (Constant.DEFAULT_VALUE_ONE.equals(scaleDetailsEntity.getIsValid())){
                return fail("无效量表，请联系管理员！");
            }
            scaleDetailsEntity.setTestNum(subjectEntityList.get(0).getTestNum());
            //获取到题目
            List<ScaleEntity> scaleEntityList = scaleService.getScaleByFlag(flag);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("subjectEntityDto2List", subjectEntityDto2List);
            jsonObject.put("ScaleDetailsEntity", scaleDetailsEntity);
            jsonObject.put("questionNum",scaleEntityList== null?0:scaleEntityList.size());
            return success(jsonObject);
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            return fail("操作失败");
        }

    }

    /**
     * 根据taskCode查询认知任务
     *
     * @return
     */
    @SafetyProcess
    @ApiOperation(value = "根据taskCode查询认知任务")
    @GetMapping("subjectInfo/CognitiveByTaskCode/{taskCode}")
    public Result CognitiveByTaskCode(@PathVariable String taskCode) {
        CognitiveTaskEntity cognitiveTaskEntity = this.cognitiveTaskService.getCognizeListByTaskCode(taskCode);
        CognitiveTaskEntityDto dto = new CognitiveTaskEntityDto(cognitiveTaskEntity);
        PromotionInfo infoBySubjectId = promotionInfoService.findInfoBySubjectId(cognitiveTaskEntity.getId());
        dto.setPrice( infoBySubjectId ==null?0.0:infoBySubjectId.getPrice());
        return success(dto);
    }

    /**
     * 获取到记忆量表字符出厂顺序
     *
     * @return
     */
    @SafetyProcess
    @ApiOperation(value = "获取到记忆量表字符出厂顺序")
    @GetMapping("subjectInfo/getRecallChar")
    public Result getRecallChar() {
        Map map = RandomUtil.recallChar();
        return success(map);
    }

    /**
     * 获取到记忆量表字符出厂顺序2
     *
     * @return
     */
    @SafetyProcess
    @ApiOperation(value = "获取到记忆量表字符出厂顺序2")
    @GetMapping("subjectInfo/getRecallCharTwo")
    public Result getRecallCharTwo() {
        Map map = RandomUtil.recallCharTwo();
        return success(map);
    }


    /**
     * 用户测试记录（我的测试）
     *
     * @return
     */
    @SafetyProcess
    @GetMapping("mineTest/{phone}/{institutionNo}")
    @ApiOperation(value = "用户测试记录（我的测试）")
    public Result mineTest(int pageNum, int pageSize, @PathVariable String phone, @PathVariable String institutionNo, String searchKey) {
        if (pageSize == 0) {
            pageSize = 20;
        }
        if(pageNum == 0){
            pageNum = 1;
        }
        Page<UserRecordsDto> userRecording = userRecordService.getUserRecording(pageNum, pageSize, phone, institutionNo, searchKey);
        //获取到列表
        List<UserRecordsDto>  list = userRecording.getContent();
        //公网版先检验是否为支付订单
        if (profileValue != null ){
            if (Constant.PROFILE_PUBLIC.equals(profileValue) ){
                for (UserRecordsDto userRecord : list){
                    PromotionInfo infoBySubjectId = promotionInfoService.findInfoBySubjectId(userRecord.getSubjectOrCognitiveId());
                    if (infoBySubjectId != null && infoBySubjectId.getPrice() != 0){
                        if (orderInfoService.checkPayOrder(userRecord.getId())){
                            userRecord.setPay("2");
                        }else {
                            userRecord.setPay("1");
                        }
                    }else {
                        userRecord.setPay("0");
                    }
                }
            }
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("userRecordEntityList",list);
        jsonObject.put("allNum", userRecording.getTotalElements());
        return success(jsonObject);
    }


    /**
     *当前量表或者认知任务历史记录
     *
     * @return
     */
    @SafetyProcess
    @GetMapping("history/{pageNum}/{pageSize}/{phone}/{institutionNo}/{flag}")
    @ApiOperation(value = "当前量表或者认知任务历史记录")
    public Result history(@PathVariable int pageNum,@PathVariable int pageSize, @PathVariable String phone, @PathVariable String institutionNo, @PathVariable String flag) {
        try {
            Page<UserRecordEntity> userRecordEntities = userRecordService.getHistoryRecord(pageNum,pageSize,phone,institutionNo,flag);
            //公网版先检验是否为支付订单
            if (profileValue != null ){
                if (Constant.PROFILE_PUBLIC.equals(profileValue) ){
                    if (CollectionUtils.isNotEmpty(userRecordEntities.getContent())){
                        userRecordEntities.getContent().forEach(userRecord->{
                            PromotionInfo infoBySubjectId = promotionInfoService.findInfoByFlag(userRecord.getFlag());
                            if (infoBySubjectId != null && infoBySubjectId.getPrice() != 0){
                                if (orderInfoService.checkPayOrder(userRecord.getId())){
                                    userRecord.setPay("2");
                                }else {
                                    userRecord.setPay("1");
                                }
                            }else {
                                userRecord.setPay("0");
                            }
                        });
                    }
                }
            }
            return success(userRecordEntities);
        }catch (Exception e){
            e.printStackTrace();
            return fail("操作异常");
        }
    }

    /**
     *当前量表或者认知任务历史记录
     *
     * @return
     */
    @SafetyProcess
    @GetMapping("countHistory/{phone}/{institutionNo}/{flag}")
    @ApiOperation(value = "历史测评统计")
    public Result countHistory(@PathVariable String phone, @PathVariable String institutionNo, @PathVariable String flag) {
        try {
            int count = userRecordService.countHistoryRecord(phone,institutionNo,flag);
            return success(count);
        }catch (Exception e){
            e.printStackTrace();
            return fail("操作异常");
        }
    }

    /**
     * 用户测试记录（我的测试）
     *
     * @return
     */
    @SafetyProcess
    @GetMapping("mineTest2/{phone}/{institutionNo}")
    @ApiOperation(value = "用户测试记录（我的测试）")
    public Result mineTest2(int pageNum, int pageSize, @PathVariable String phone, @PathVariable String institutionNo, String searchKey) {
        Page<UserRecordEntity> userRecording = userRecordService.getUserRecording2(pageNum, pageSize, phone, institutionNo, searchKey);
        //获取到列表
        List<UserRecordEntity>  list = userRecording.getContent();
        //获取到所有收费信息
        List<PromotionInfo> infos = promotionInfoService.findAll();
        //公网版先检验是否为支付订单
        if (profileValue != null ){
            if (Constant.PROFILE_PUBLIC.equals(profileValue) ){
                for (UserRecordEntity userRecord : list){
                    for (PromotionInfo info:infos){
                        if (!userRecord.getFlag().equals(info.getFlag())){
                            continue;
                        }
                        if ( info.getPrice() != 0){
                            if (orderInfoService.checkPayOrder(userRecord.getId())){
                                userRecord.setPay("2");
                            }else {
                                userRecord.setPay("1");
                            }
                        }else {
                            userRecord.setPay("0");
                        }
                        break;
                    }
//                    PromotionInfo infoBySubjectId = promotionInfoService.findInfoByFlag(userRecord.getFlag());
//                    if (infoBySubjectId != null && infoBySubjectId.getPrice() != 0){
//                        if (orderInfoService.checkPayOrder(userRecord.getId())){
//                            userRecord.setPay("2");
//                        }else {
//                            userRecord.setPay("1");
//                        }
//                    }else {
//                        userRecord.setPay("0");
//                    }
                }
            }
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("userRecordEntityList",list);
        jsonObject.put("allNum", userRecording.getTotalElements());
        return success(jsonObject);
    }



    /**
     * 用户查询枪林弹雨
     *
     * @return
     */
    @SafetyProcess
    @GetMapping("GUNSBULLETS/{userId}")
    @ApiOperation(value = "用户查询枪林弹雨记录")
    public Result GUNSBULLETS(@PathVariable String userId) {
        UserEntity one = this.userService.getOne(userId);
        List<UserRecordEntity> gunsbullets = this.userRecordService.getGUNSBULLETS(one.getPhone(), one.getInstitutionNo());
        return success(gunsbullets);
    }


    /**
     * 根据id查询测试详细信息
     *
     * @return
     */
    @SafetyProcess
    @GetMapping("/getRecordById")
    @ApiOperation(value = "根据id查询测试详细信息")
    public Result getRecordById(String id) {
        //公网版先检验是否为支付订单
        if (profileValue != null ){
            if (Constant.PROFILE_PUBLIC.equals(profileValue) ){
                //认知任务暂时不做支付处理
                UserRecordEntity userRecordEntity = userRecordService.getUserRecordById(id);
                if (userRecordEntity.getType().equals("0")){
                    SubjectEntity subjectEntity = this.subjectService.getSubjectEntityByFlag(userRecordEntity.getFlag());
                    PromotionInfo infoBySubjectId = promotionInfoService.findInfoBySubjectId(subjectEntity.getId());
                    if (infoBySubjectId != null && infoBySubjectId.getPrice() != 0){
                        if (userRecordEntity != null && Constant.DEFAULT_VALUE_ZERO.equals(userRecordEntity.getType())){
                            if (!orderInfoService.checkPayOrder(id)){
                                return fail("未支付");
                            }
                        }
                    }
                }
            }
        }

        //获取测试记录信息
        UserRecordEntity userRecordEntity = this.userRecordService.getUserRecordById(id);
        if (userRecordEntity == null){
            return fail("参数错误");
        }
        //判断是否达到最大测试次数
        InstitutionEntity entity = institutionService.findByInstitutionNo(userRecordEntity.getInstitutionNo());
        if (Constant.DEFAULT_VALUE_ONE.equals(entity.getIsTestNum().toString())){
            //获取该机构下测试数据
            int count = userRecordService.finAllByInstitutionNo(userRecordEntity.getInstitutionNo());
            if (count> entity.getTestNum()){
                if (entity.getTestNum()==0){
                    return fail("测试次数已达上限，请联系机构管理员");
                }
                //获取到最后一条测试记录
                String last = userRecordService.findByTestNum(entity.getInstitutionNo(),entity.getTestNum()-1);
                if (last != null){
                    int result = DateUtil.compare(DateUtil.parse(userRecordEntity.getTestDate(), DatePattern.CHINESE_DATE_TIME_PATTERN),DateUtil.parse(last,DatePattern.CHINESE_DATE_TIME_PATTERN));
                    if (result > 0){
                        return fail("测试次数已达上限，请联系机构管理员");
                    }
                }
            }
        }

        //获取测试人员信息
        UserEntity userInfo = this.userService.findPhoneAndInstitutionNoAndRoleType(userRecordEntity.getPhone(), userRecordEntity.getInstitutionNo(),UserRole.COMMON.getType());
        UserFileEntity userFileEntity = this.userFileService.findByUserId(userInfo.getId());
        if (userFileEntity != null){
            userInfo.setAvatarUrl(userFileEntity.getPath());
        }

        String flag = userRecordEntity.getFlag();
        String type = userRecordEntity.getType();
        List<SubjectEntity> subjectByFlag;
        JSONObject result = new JSONObject();
        if ("0".equals(type)) {
            subjectByFlag = subjectService.getSubjectByFlag(flag);
            result.put("subject", subjectByFlag.get(0));
        }else if ("1".equals(type)) {
            CognitiveTaskEntity cognitiveTask = this.cognitiveTaskService.getCognizeListByTaskCode(flag);
            result.put("cognitiveTask", cognitiveTask);
        }

        result.put("userRecordEntity", userRecordEntity);
        result.put("userInfo", userInfo);

        return success(result);
    }



    //@SafetyProcess
    @PostMapping("/importSubjectByJson")
    @ApiOperation(value = "第一批导入json格式量表")
    public Result importSubjectByJson(@RequestBody JSONObject jsonObject) {
        System.out.println("jsonobject:" + jsonObject);

        //量表标志自动生成唯一值，yyyyMMddHHmmss
        String flag = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        JSONObject result = jsonObject.getJSONObject("result");
        //根据量表中文名查询,判断该量表是否存在
        SubjectEntity subject = this.subjectService.getSubjectByname(result.getString("title"));
        if (subject != null) {
            return fail("该量表已存在！");
        }
        //创建量表实体类，并传入数据
        SubjectEntity subjectEntity = new SubjectEntity();
        subjectEntity.setName(result.getString("title"));
        subjectEntity.setFlag(flag);
        //类型默认量表
        subjectEntity.setType("0");
        //新增量表默认为热门测试
        subjectEntity.setIsHot("1");
        //新增量表默认为最新测试
        subjectEntity.setIsNew(1);
        subjectEntity.setDescription(result.getString("desc"));
        subjectEntity.setUploader("雷煜");
        //subjectEntity.setEName(eName);
        subjectEntity.setStatus(0);
        subjectEntity.setFileName("null");
        //计分原则
        String scoringPrinciple = "";

        //获取量表题目信息
        JSONArray items = result.getJSONArray("items");
        for (int i = 0; i < items.size(); i++) {
            JSONObject item = items.getJSONObject(i);
            ScaleEntity scaleEntity = new ScaleEntity();
            scaleEntity.setQuestionNo(item.getString("index"));
            scaleEntity.setSerialNo(item.getString("index"));
            scaleEntity.setAnswer(item.getString("name"));
            //答案选项
            String checkItems = "";
            scaleEntity.setQuestionType(Constant.MAGIC_NUM_0);
            scaleEntity.setWeight("");
//            量表模板不提供分值
            scaleEntity.setScore("");
            scaleEntity.setFlag(flag);
            scaleEntity.setScoreDirection("1");
            //获取题目选项信息
            JSONArray options = item.getJSONArray("options");
            for (int y = 0; y < options.size(); y++) {
                JSONObject option = options.getJSONObject(y);
                AnswerEntity answerEntity = new AnswerEntity();
                answerEntity.setFlag(flag);
                answerEntity.setQuestionNo(item.getString("index"));
                answerEntity.setName(option.getString("name"));
                answerEntity.setOptions(option.getString("select"));
                answerEntity.setQuestionType("0");
                answerEntity.setScore(option.getString("score"));
                answerEntity.setScoreDirection("1");
                this.answerService.saveAnswer(answerEntity);

                if (y + 1 == options.size()) {
                    checkItems = checkItems + option.getString("name");
                } else {
                    checkItems = checkItems + option.getString("name") + "；";
                }


            }
            scaleEntity.setCheckItems(checkItems);
            this.scaleService.saveScale(scaleEntity);
            System.out.println(scaleEntity.toString());
        }

        JSONArray scores = result.getJSONArray("scores");
        for (int i = 0; i < scores.size(); i++) {
            JSONObject score = scores.getJSONObject(i);
            int scoreStart = score.getInteger("scoreStart");
            int scoreEnd = score.getInteger("scoreEnd");
            String desc = score.getString("desc");
            String improvementSuggestions = score.getString("improvementSuggestions");
            scoringPrinciple = scoringPrinciple + scoreStart + "-" + scoreEnd + "；" + desc;
            if (improvementSuggestions != null) {
                scoringPrinciple = scoringPrinciple + "；" + improvementSuggestions;
            }
            ScaleMarksEntity scaleMarksEntity = new ScaleMarksEntity();
            scaleMarksEntity.setFlag(flag);
            scaleMarksEntity.setImprovementSuggestions(improvementSuggestions);
            scaleMarksEntity.setSymptom(score.getString("desc"));
            scaleMarksEntity.setScoreEnd(String.valueOf(scoreEnd));
            scaleMarksEntity.setScoreStart(String.valueOf(scoreStart));
            //TODO 设置评分规则表默认值
            scaleMarksEntity.setNameExplain("无");
            scaleMarksEntity.setReference("无");
            scaleMarksEntity.setSuggestion("无");
            scaleMarksEntity.setIsTotalScoreExplain("否");
            this.scaleMarksService.saveScaleMarks(scaleMarksEntity);
        }
        subjectEntity.setScoringPrinciple(scoringPrinciple);
        this.subjectService.save(subjectEntity);
        System.out.println(subjectEntity);
        return success();
    }

    @PostMapping("/importSubjectByJsonb")
    @ApiOperation(value = "第二批导入json格式量表")
    public Result importSubjectByJsonb(@RequestBody JSONObject result) {
        System.out.println("jsonobject:" + result);

        //量表标志自动生成唯一值，yyyyMMddHHmmss
        String flag = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        //根据量表中文名查询,判断该量表是否存在
        SubjectEntity subject = this.subjectService.getSubjectByname(result.getString("title"));
        if (subject != null) {
            return fail("该量表已存在！");
        }
        //创建量表实体类，并传入数据
        SubjectEntity subjectEntity = new SubjectEntity();
        subjectEntity.setName(result.getString("title"));
        subjectEntity.setFlag(flag);
        //类型默认量表
        subjectEntity.setType("0");
        //新增量表默认为热门测试
        subjectEntity.setIsHot("1");
        //新增量表默认为最新测试
        subjectEntity.setIsNew(1);
        subjectEntity.setDescription(result.getString("instruction"));
        subjectEntity.setUploader("雷煜");
        //subjectEntity.setEName(eName);
        subjectEntity.setStatus(0);
        subjectEntity.setFileName("null");
        subjectEntity.setScaleLimit("public");
        //计分原则
        String scoringPrinciple = "";

        //获取量表题目信息
        JSONArray items = result.getJSONArray("items");
        for (int i = 0; i < items.size(); i++) {
            JSONObject item = items.getJSONObject(i);
            ScaleEntity scaleEntity = new ScaleEntity();
            scaleEntity.setQuestionNo(item.getString("index"));
            scaleEntity.setSerialNo(item.getString("index"));
            scaleEntity.setAnswer(item.getString("name"));
            //答案选项
            String checkItems = "";
            scaleEntity.setQuestionType(Constant.MAGIC_NUM_0);
            scaleEntity.setWeight("");
//            量表模板不提供分值
            scaleEntity.setScore("");
            scaleEntity.setFlag(flag);
            scaleEntity.setScoreDirection("1");
            //获取题目选项信息
            JSONArray options = item.getJSONArray("options");
            for (int y = 0; y < options.size(); y++) {
                JSONObject option = options.getJSONObject(y);
                AnswerEntity answerEntity = new AnswerEntity();
                answerEntity.setFlag(flag);
                answerEntity.setQuestionNo(item.getString("index"));
                answerEntity.setName(option.getString("select"));
                answerEntity.setOptions("");
                answerEntity.setQuestionType("0");
                answerEntity.setScore(option.getString("score"));
                answerEntity.setScoreDirection("1");
                this.answerService.saveAnswer(answerEntity);

                if (y + 1 == options.size()) {
                    checkItems = checkItems + option.getString("select");
                } else {
                    checkItems = checkItems + option.getString("select") + "；";
                }
            }
            scaleEntity.setCheckItems(checkItems);
            this.scaleService.saveScale(scaleEntity);
            System.out.println(scaleEntity.toString());
        }

        JSONArray scores = result.getJSONArray("scores");
        for (int i = 0; i < scores.size(); i++) {
            JSONObject score = scores.getJSONObject(i);
            int scoreStart = score.getInteger("scoreStart");
            int scoreEnd = score.getInteger("scoreEnd");
            String desc = score.getString("desc");
            scoringPrinciple = scoringPrinciple + scoreStart + "-" + scoreEnd + "；" + desc;
            ScaleMarksEntity scaleMarksEntity = new ScaleMarksEntity();
            scaleMarksEntity.setFlag(flag);
            scaleMarksEntity.setImprovementSuggestions("");
            scaleMarksEntity.setSymptom(score.getString("desc"));
            scaleMarksEntity.setScoreEnd(String.valueOf(scoreEnd));
            scaleMarksEntity.setScoreStart(String.valueOf(scoreStart));
            //TODO 设置评分规则表默认值
            scaleMarksEntity.setNameExplain("无");
            scaleMarksEntity.setReference("无");
            scaleMarksEntity.setSuggestion("无");
            scaleMarksEntity.setIsTotalScoreExplain("否");
            this.scaleMarksService.saveScaleMarks(scaleMarksEntity);
        }
        subjectEntity.setScoringPrinciple(scoringPrinciple);
        this.subjectService.save(subjectEntity);
        System.out.println(subjectEntity);
        return success();
    }


    /**
     * 删除字段多余字符
     *
     * @return
     */
    //@SafetyProcess
    //@GetMapping("deleteChar")
    //@ApiOperation(value = "删除字段多余字符")
    public Result deleteChar() {
        List<SubjectEntity> subjectEntities = this.subjectService.findAll("0");
        for (SubjectEntity subjectEntity : subjectEntities) {
            if (subjectEntity.getScoringPrinciple() != null) {
                String scoring = subjectEntity.getScoringPrinciple().replaceAll("\\<[^\\<^\\>]*\\>", "");
                scoring = scoring.replace("；null", "");
                this.subjectService.updateById(subjectEntity.getId(), scoring);
            }
        }
        List<ScaleMarksEntity> scaleMarksEntities = this.scaleMarksService.findAll();
        for (ScaleMarksEntity scaleMarksEntity : scaleMarksEntities) {
            String symptom = null;
            String improvement = null;
            if (scaleMarksEntity.getSymptom() != null) {
                symptom = scaleMarksEntity.getSymptom().replaceAll("\\<[^\\<^\\>]*\\>", "");
            }
            if (scaleMarksEntity.getImprovementSuggestions() != null) {
                improvement = scaleMarksEntity.getImprovementSuggestions().replaceAll("\\<[^\\<^\\>]*\\>", "");
            }
            this.scaleMarksService.updateById(scaleMarksEntity.getId(), symptom, improvement);
        }

        return success();
    }

    /**
     * 处理用户测试结果数据格式
     *
     * @return
     */
    //@SafetyProcess
    @GetMapping("userRecord")
    @ApiOperation(value = "处理用户测试结果数据格式")
    public Result userRecord() {
        List<UserRecordEntity> userRecordEntities = this.userRecordService.findAll1();
        for (UserRecordEntity userRecordEntity : userRecordEntities) {
            if (!userRecordEntity.getFlag().contains("YATAI") || !userRecordEntity.getFlag().equals("ANTFISH")) {
                //计算结果
                JSONArray dbJsonList = JSONArray.parseArray(userRecordEntity.getTestResult());
                JSONObject dbJson = dbJsonList.getJSONObject(0);
                JSONArray tableContext = dbJson.getJSONArray("tableContext");
                String testResults = new String();
                for (int i = 0; i < tableContext.size(); i++) {
                    JSONObject jsonObject = tableContext.getJSONObject(i);
                    if (i == tableContext.size() - 1) {
                        testResults += jsonObject.getString("name") + ":" + jsonObject.getJSONArray("value").getString(0);
                    } else {
                        testResults += jsonObject.getString("name") + ":" + jsonObject.getJSONArray("value").getString(0) + ";";
                    }

                }
            }
        }
        return success();
    }


    /* V1版本，暂时保留
    @ApiOperation(value = "用户导入")
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("userImport")
    public Result userImport(String institutionNo, MultipartFile file, HttpServletResponse response) throws Exception {
        if (file == null) {
            return fail("文件为空");
        }
        if (institutionNo == null) {
            return fail("机构编号为空");
        }
        //String message = "提交成功";
        String filePath = "";//用户信息上传之后生成的用户名密码文件保存路径
        String fileName = file.getOriginalFilename();
        List<List<Object>> datas = ExcelUtil.getBankListByExcelForUserImport(file.getInputStream(), fileName);
        if(datas.size() <= 0){
            return fail("内容为空");
        }
        //插入数据库信息
        List<UserEntity> userListDB = new ArrayList<>();
        //生成导入后用户信息
        List<UserEntity> userLists = new ArrayList<>();

        StringBuilder result = new StringBuilder();
        //result.append("账号：");
        //判断是否有已经存在数据库的
        boolean isExist = false;
        //UserEntity tempUserDB;
        String defaultGroupId = null;
        try {
            int y = 0;
            for (int i = 0; i < datas.size(); i++) {
                List<Object> users = datas.get(i);
                if (users.get(0) == null || users.get(0) == "" || users.get(1) == null || users.get(1) == "" || users.get(2) == null || users.get(2) == ""
                || users.get(3) == null || users.get(3) == "" || users.get(4) == null || users.get(4) == "" || users.get(5) == null || users.get(5) == "") {
                    y = i + 1;
                    result.append("第" + y +"条数据信息不完整").append("\r\n");
                    isExist = true;
                    continue;
                }
                //北京师范大学亚太实验学校, 陈亚浩2, 男, 2001-10-01, 学生, , 六年级一班, null, null
                //插入数据库的信息
                UserEntity tempUserDB = new UserEntity();
                //导入成功用户信息
                UserEntity userEntity = new UserEntity();
                tempUserDB.setInstitutionName(users.get(0).toString());
                tempUserDB.setPetName(users.get(1).toString());
                userEntity.setInstitutionName(users.get(0).toString());
                userEntity.setPetName(users.get(1).toString());
                userEntity.setGender(users.get(2).toString());
                if ("男".equals(users.get(2).toString())) {
                    tempUserDB.setGender("0");
                } else {
                    tempUserDB.setGender("1");
                }
                tempUserDB.setBirthday(users.get(3).toString());
                tempUserDB.setProfession(users.get(4).toString());
                tempUserDB.setAdditionInfo(users.get(5).toString());
                userEntity.setBirthday(users.get(3).toString());
                userEntity.setProfession(users.get(4).toString());
                userEntity.setAdditionInfo(users.get(5).toString());
                int repeatNum = userRepeatNameNumService.testOrNotNamePinyin(institutionNo, getPinyin(users.get(1).toString()));
                if (users.size() > 6) {
                    if (null == users.get(6) || users.get(6).equals("")) {
                        tempUserDB.setPhone(repeatNum == 0 ? getPinyin(users.get(1).toString()) : getPinyin(users.get(1).toString()) + repeatNum);
                        userEntity.setPhone(repeatNum == 0 ? getPinyin(users.get(1).toString()) : getPinyin(users.get(1).toString()) + repeatNum);
                    } else {
                        tempUserDB.setPhone(users.get(6).toString());
                        userEntity.setPhone(users.get(6).toString());
                    }
                } else {
                    tempUserDB.setPhone(repeatNum == 0 ? getPinyin(users.get(1).toString()) : getPinyin(users.get(1).toString()) + repeatNum);
                    userEntity.setPhone(repeatNum == 0 ? getPinyin(users.get(1).toString()) : getPinyin(users.get(1).toString()) + repeatNum);
                }
                if (users.size() > 7) {
                    if (null == users.get(7) || users.get(7).equals("")) {
                        tempUserDB.setPassword(DigestUtils.md5DigestAsHex(Constant.DEFAULT_PASSWORD.getBytes(StandardCharsets.UTF_8)));
                        userEntity.setPassword(Constant.DEFAULT_PASSWORD);
                    } else {
                        tempUserDB.setPassword(DigestUtils.md5DigestAsHex(users.get(7).toString().getBytes(StandardCharsets.UTF_8)));
                        userEntity.setPassword(users.get(7).toString());
                    }
                } else {
                    tempUserDB.setPassword(DigestUtils.md5DigestAsHex(Constant.DEFAULT_PASSWORD.getBytes(StandardCharsets.UTF_8)));
                    userEntity.setPassword(Constant.DEFAULT_PASSWORD);
                }

//                tempUserDB.setPhone(getPinyin(users.get(1).toString()));
                tempUserDB.setInstitutionNo(institutionNo);
                tempUserDB.setUserStatus("2");
                userEntity.setInstitutionNo(institutionNo);
                userEntity.setUserStatus("2");
                //设置组id，未分组时组id为0
                if (defaultGroupId == null) {
                    GroupEntity groupByInstitutionNoAndName = this.groupInfoService.findGroupByInstitutionNoAndName(tempUserDB.getInstitutionNo(), Constant.DEFAULT_GROUP_NAME);
                    if (groupByInstitutionNoAndName == null) {
                        GroupEntity groupEntity = new GroupEntity();
                        groupEntity.setGroupName(Constant.DEFAULT_GROUP_NAME);
                        groupEntity.setInstitutionNo(tempUserDB.getInstitutionNo());
                        groupEntity = this.groupInfoService.addGroup(groupEntity);
                        //创建权限
                        List<InstitutionAuthEntity> institutionAuthEntityList = this.institutionAuthService.getByInstitutionNo(tempUserDB.getInstitutionNo());
                        for (int mi = 0; mi < institutionAuthEntityList.size(); mi++) {
                            InstitutionAuthEntity institutionAuthEntity = new InstitutionAuthEntity();
                            GroupAuthEntity groupAuthEntity = new GroupAuthEntity();
                            groupAuthEntity.setBId(institutionAuthEntity.getBId());
                            groupAuthEntity.setGroupId(groupEntity.getId());
                            groupAuthEntity.setType(institutionAuthEntity.getType());
                            this.groupAuthService.addGroupAuth(groupAuthEntity);
                        }
                        defaultGroupId = groupEntity.getId();
                    } else {
                        defaultGroupId = groupByInstitutionNoAndName.getId();
                    }
                }
                tempUserDB.setGId(defaultGroupId);
                tempUserDB.setModelPhone("0");
                tempUserDB.setRoleType(UserRole.COMMON.getType());
                userEntity.setGId(defaultGroupId);
                userEntity.setModelPhone("0");
                userEntity.setRoleType(UserRole.COMMON.getType());

                //查看当前用户是否已经在数据库存在
                UserEntity phoneAndInstitutionNo = userService.findPhoneAndInstitutionNo(tempUserDB.getPhone(), institutionNo);
                if (phoneAndInstitutionNo != null) {
                    y = i + 1;
                    result.append("第" + y +"条数据账号" + phoneAndInstitutionNo.getPhone() + "已存在").append("\r\n");
                    isExist = true;
                    continue;
                }
                this.userService.save(tempUserDB);
                userListDB.add(tempUserDB);
                userLists.add(userEntity);

            }
            if (OSUtil.isLinux()) {
                filePath = "./userImport/" + institutionNo + "/" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "/";
            } else {
                filePath = "./userImport/" + institutionNo + "/" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "/";
            }
            ExcelUtil.createExcelFileForPublic(UserEntity.class, userLists, null, new ExcelClass().userExportExcel(), fileName, filePath);
            if (isExist) {
                result.append("，跳过该信息。(请检查该信息)");
                return success(filePath + fileName, result.toString());
            } else {
                return success(filePath + fileName, "批量导入成功");
            }
        } catch (Exception exception) {

            exception.printStackTrace();
            return fail("导入失败，请联系管理员");
        }
    }*/

    @ApiOperation(value = "用户导入")
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("userImport")
    public Result userImport(String institutionNo, MultipartFile file, HttpServletResponse response) throws Exception {
        if (file == null) {
            return fail("文件为空");
        }
        if (institutionNo == null) {
            return fail("机构编号为空");
        }

        String fileName = file.getOriginalFilename();
        List<List<Object>> datas = ExcelUtil.getBankListByExcelForUserImport(file.getInputStream(), fileName);
        if(datas.size() <= 0){
            return fail("内容为空");
        }

        StringBuilder result = new StringBuilder();
        //判断是否有已经存在数据库的
        boolean isExist = false;
        String defaultGroupId = null;
        try {
            int y = 0;
            for (int i = 0; i < datas.size(); i++) {
                List<Object> users = datas.get(i);
                if (users.get(0) == null || users.get(0) == "" || users.get(1) == null || users.get(1) == "" || users.get(2) == null || users.get(2) == "") {
                    y = i + 1;
                    result.append("第" + y +"条数据信息不完整").append("\r\n");
                    isExist = true;
                    continue;
                }
                String petName = users.get(0).toString();
                if (petName.length() > 18 || petName.contains(" ")){
                    y = i + 1;
                    result.append("第" + y +"条数据姓名长度大于18位或有空格").append("\r\n");
                    isExist = true;
                    continue;
                }
                String phone = users.get(1).toString();
                if (phone.length() > 18 || phone.length() < 3 || phone.contains(" ")){
                    y = i + 1;
                    result.append("第" + y +"条数据账号长度未在3~18位之间或有空格").append("\r\n");
                    isExist = true;
                    continue;
                }
                String password = users.get(2).toString();
                if (password.length() < 6 || password.length() > 18 || password.contains(" ")){
                    y = i + 1;
                    result.append("第" + y +"条数据密码长度未在6~18位之间或有空格").append("\r\n");
                    isExist = true;
                    continue;
                }
                //插入数据库的信息
                UserEntity tempUserDB = new UserEntity();
                //设置组id，未分组时组id为0
                if (defaultGroupId == null) {
                    GroupEntity groupByInstitutionNoAndName = this.groupInfoService.findGroupByInstitutionNoAndName(institutionNo, Constant.DEFAULT_GROUP_NAME);
                    if (groupByInstitutionNoAndName == null) {
                        GroupEntity groupEntity = new GroupEntity();
                        groupEntity.setGroupName(Constant.DEFAULT_GROUP_NAME);
                        groupEntity.setInstitutionNo(institutionNo);
                        groupEntity = this.groupInfoService.addGroup(groupEntity);
                        //创建权限
                        List<InstitutionAuthEntity> institutionAuthEntityList = this.institutionAuthService.getByInstitutionNo(institutionNo);
                        for (int mi = 0; mi < institutionAuthEntityList.size(); mi++) {
                            InstitutionAuthEntity institutionAuthEntity = new InstitutionAuthEntity();
                            GroupAuthEntity groupAuthEntity = new GroupAuthEntity();
                            groupAuthEntity.setBId(institutionAuthEntity.getBId());
                            groupAuthEntity.setGroupId(groupEntity.getId());
                            groupAuthEntity.setType(institutionAuthEntity.getType());
                            this.groupAuthService.addGroupAuth(groupAuthEntity);
                        }
                        defaultGroupId = groupEntity.getId();
                    } else {
                        defaultGroupId = groupByInstitutionNoAndName.getId();
                    }
                }
                InstitutionEntity institutionEntity = this.institutionService.findByInstitutionNo(institutionNo);
                /*
                  `gender` varchar(2) NOT NULL COMMENT '性别(0-男；1-女)',
                  `birthday` varchar(15) NOT NULL COMMENT '出生日期',
                  `profession` varchar(50) DEFAULT NULL COMMENT '职业',
                  `addition_info` varchar(500) DEFAULT NULL COMMENT '附加信息',
                  `model_phone` varchar(11) DEFAULT '0' COMMENT '用户手机号：0->用户不填手机号', 可为空
                  */
                tempUserDB.setInstitutionName(institutionEntity.getInstitutionName());
                //姓名、账号、密码格式未效验
                tempUserDB.setPetName(users.get(0).toString());
                tempUserDB.setPhone(users.get(1).toString());
                tempUserDB.setPassword(DigestUtils.md5DigestAsHex(users.get(2).toString().getBytes(StandardCharsets.UTF_8)));
                tempUserDB.setGender(Constant.DEFAULT_VALUE_ZERO);
                tempUserDB.setBirthday("2001-01-01");
                tempUserDB.setInstitutionNo(institutionNo);
                tempUserDB.setUserStatus(UserStatus.PERFECT.getType());
                tempUserDB.setGId(defaultGroupId);
                tempUserDB.setModelPhone(Constant.DEFAULT_VALUE_ZERO);
                tempUserDB.setRoleType(UserRole.COMMON.getType());

                //查看当前用户是否已经在数据库存在
                UserEntity phoneAndInstitutionNo = userService.findPhoneAndInstitutionNoAndRoleType(tempUserDB.getPhone(), institutionNo,Constant.DEFAULT_VALUE_ONE);
                if (phoneAndInstitutionNo != null) {
                    y = i + 1;
                    result.append("第" + y +"条数据账号" + phoneAndInstitutionNo.getPhone() + "已存在").append("\r\n");
                    isExist = true;
                    continue;
                }
                this.userService.save(tempUserDB);
            }
            if (isExist) {
                result.append("，跳过该信息。(请检查该信息)");
                return success("", result.toString());
            } else {
                return success("", "批量导入成功");
            }
        } catch (Exception exception) {
            exception.printStackTrace();
            return fail("导入失败，请联系管理员");
        }
    }

    @PostMapping("/saveCognitiveTask")
    @ApiOperation(value = "添加认知任务信息")
    public Result completeTest(@RequestBody JSONArray jsonArray) throws Exception {
        List<CognitiveTaskEntity> cognitiveTaskEntityList = jsonArray.toJavaList(CognitiveTaskEntity.class);
        for (CognitiveTaskEntity cognitiveTaskEntity : cognitiveTaskEntityList) {
            this.cognitiveTaskService.save(cognitiveTaskEntity);
        }
        return null;
    }


    @ApiOperation(value = "用户模板下载")
    @GetMapping("/download/userTemplateDownload")
    public String userTemplateDownload(HttpServletResponse response) {
        String filePath = "";
        if (OSUtil.isLinux()) {
            filePath = "./userTemplate/importTemplate.xlsx";
        } else {
            filePath = "./userTemplate/importTemplate.xlsx";
        }
        File fileReturn = new File(filePath);
        response.reset();
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setContentLength((int) fileReturn.length());
        response.setHeader("Content-Disposition", "attachment;filename=template.xlsx");

        byte[] buffer = new byte[1024];
        BufferedInputStream bis = null;
        try {
            bis = new BufferedInputStream(Files.newInputStream(fileReturn.toPath()));
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
            return "下载成功";
        } catch (Exception e) {
            e.printStackTrace();
            return "下载失败";
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @ApiOperation(value = "用户导入结果下载")
    @GetMapping("/download/userImportResult")
    public String userImportResult(HttpServletResponse response, String filePath) {

        File fileReturn = new File(filePath);
        response.reset();
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setContentLength((int) fileReturn.length());
        response.setHeader("Content-Disposition", "attachment;filename=userImportResult.xlsx");

        byte[] buffer = new byte[1024];
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
            fis = new FileInputStream(fileReturn);
            bis = new BufferedInputStream(fis);
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
            return "下载成功";
        } catch (Exception e) {
            e.printStackTrace();
            return "下载失败";
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    @ApiOperation(value = "SCL90--各个维度评分规则--excel导入")
    @PostMapping("/import/marks/scl901/{flag}")
    public Result Scl90ExcelImport(@PathVariable String flag, MultipartFile file) throws Exception {
        if (file == null) {
            return fail("文件为空");
        }
        if (flag == null) {
            return fail("所属量表标识为空");
        }
        List<ScaleMarksEntity> scaleMarksByFlag = scaleMarksService.getScaleMarksByFlag(flag);
        if (scaleMarksByFlag.size() != 0) {
            return fail("该量表的维度评分信息已入库，请联系管理员");
        }
        //用户信息上传之后生成的用户名密码文件保存路径
        String fileName = file.getOriginalFilename();
        List<List<Object>> marks = ExcelUtil.getBankListByExcelForUserImport(file.getInputStream(), fileName);
        try {
            for (List<Object> mark : marks) {
                System.out.println(mark);
                //因子（维度名称）	最低分（起始分）最高分(结束分) 常模参考值 标准差 结论（该分段症状）
                //因子解释 等级解释(该分段指导语） 建议 是否为总分结论
                //图表信息iconInfo isIconFlag
                ScaleMarksEntity tempUserDB = new ScaleMarksEntity();
                tempUserDB.setName(String.valueOf(mark.get(0)));
                tempUserDB.setScoreStart(String.valueOf(mark.get(1)));
                tempUserDB.setScoreEnd(String.valueOf(mark.get(2)));
                if (("").equals(String.valueOf(mark.get(3)))) {
                    tempUserDB.setReference("无");
                } else {
                    tempUserDB.setReference(String.valueOf(mark.get(3)));
                }

                if (("无").equals(tempUserDB.getReference())) {
                    tempUserDB.setStandardDeviation("无");
                } else {
                    tempUserDB.setStandardDeviation(String.valueOf(mark.get(4)));
                }

                tempUserDB.setSymptom(String.valueOf(mark.get(5)));
                tempUserDB.setNameExplain(String.valueOf(mark.get(6)));
                tempUserDB.setImprovementSuggestions(String.valueOf(mark.get(7)));
                tempUserDB.setSuggestion(String.valueOf(mark.get(8)));
                tempUserDB.setIsTotalScoreExplain(String.valueOf(mark.get(9)));
                tempUserDB.setFlag(flag);
                System.out.println(tempUserDB.toString());
                this.scaleMarksService.saveScaleMarks(tempUserDB);
            }
        } catch (Exception exception) {
            exception.printStackTrace();
            return fail("导入失败，请联系管理员");
        }
        return success("入库成功");
    }

    @ApiOperation(value = "新增/更新 认知任务",notes = "id 主键,新增时为空更新必传,  description 任务说明,name 认知任务名称,imageUrl 图片路径,imageName 图片名称," +
            "testDescription 测试任务描述,testNum 测试次数,type 类型：0-量表；1-认知任务,pageUrl 分页路径,testExplain 任务解释,status 状态：0-可用；9-不可用,scaleLimit 认知任务权限:private 私密  public 公开" +
            "no 编号，用于排序,mobileDescription 移动端任务说明,mobilePageUrl 移动端前台页面路径,mobileTestDescription 移动端测试任务描述,mobileStatus 移动端任务状态：0-不可用；1-可用," +
            "reportVersion 报告版本：1-老模板报告；2-新模板报告,practice 类型：1-有练习测试；2-无练习测试")
    @PostMapping("/cognize/save")
    @SafetyProcess
    public Result saveCognize(@RequestBody String json) {
        CognitiveTaskEntity taskEntity = JSONObject.parseObject(JSONObject.parseObject(json).getString("data")).toJavaObject(CognitiveTaskEntity.class);
        if(StringUtils.isBlank(taskEntity.getTaskCode())){
            return fail("标识为空");
        }
        if(StringUtils.isBlank(taskEntity.getMobileStatus())){
            taskEntity.setMobileStatus(Constant.MAGIC_NUM_0);
        }
        if(StringUtils.isBlank(taskEntity.getReportVersion())){
            taskEntity.setReportVersion(Constant.MAGIC_NUM_1);
        }
        if(StringUtils.isBlank(taskEntity.getPractice())){
            taskEntity.setPractice(Constant.MAGIC_NUM_2);
        }
        this.cognitiveTaskService.save(taskEntity);

        return success();
    }

    /**
     * 汉字转拼音
     *
     * @param china
     * @return
     */
    public static String getPinyin(String china) {
        HanyuPinyinOutputFormat formart = new HanyuPinyinOutputFormat();
        formart.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        formart.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        formart.setVCharType(HanyuPinyinVCharType.WITH_V);
        char[] arrays = china.trim().toCharArray();
        StringBuilder result = new StringBuilder();
        try {
            for (int i = 0; i < arrays.length; i++) {
                char ti = arrays[i];
                if (Character.toString(ti).matches("[\\u4e00-\\u9fa5]")) { //匹配是否是中文
                    String[] temp = PinyinHelper.toHanyuPinyinStringArray(ti, formart);
                    result.append(temp[0]);
                } else {
                    result.append(ti);
                }
            }
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            e.printStackTrace();
        }
        return result.toString();
    }






}
