package com.rf.psychological.scale.rest;

import com.rf.psychological.base.rest.BaseController;
import com.rf.psychological.dao.model.*;
import com.rf.psychological.group.dao.model.GroupAuthEntity;
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.service.InstitutionAuthService;
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.utils.Constant;
import com.rf.psychological.utils.ExcelUtil;
import com.rf.psychological.utils.OSUtil;
import com.rf.psychological.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Api(tags = "量表导入新模板接口")
@RestController
public class importTest extends BaseController {

    @Autowired
    private ScaleService scaleService;
    @Autowired
    private SubjectService subjectService;
    @Autowired
    private AnswerService answerService;

    @Autowired
    private ScaleMarksService scaleMarksService;

    @Autowired
    private DimensionService dimensionService;

    @Autowired
    private CategorySubjectService categorySubjectService;

    @Autowired
    private InstitutionAuthService institutionAuthService;

    @Autowired
    private GroupAuthService groupAuthService;

    @Autowired
    private GroupInfoService groupInfoService;

    /**
     * 导入量表
     * 1、量表名称  2、量表指导语  3、量表录入人
     * @return
     */
    @PostMapping("importTest")
    @ApiOperation(value = "量表导入测试")
    public Result importScale(String scaleName, String scaleDesc, String uploader, String eName, String scoringPrinciple, String institutionNo, String filePath) throws Exception {
        File file = new File(filePath);
        if (file == null) {
            Files.delete(Paths.get(filePath));
            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(DESede.encryptString(scaleDesc));
        subjectEntity.setDescription(scaleDesc);
        subjectEntity.setUploader(uploader);
        subjectEntity.setEName(eName);
        subjectEntity.setScoringPrinciple(scoringPrinciple);
        subjectEntity.setScaleLimit("public");
        subjectEntity.setStatus(0);
        subjectEntity.setIconInfo("无");
        subjectEntity.setMen("0");
        /*if(people.contains("0")){
            people = "0";
        }*/
        //subjectEntity.setMen(people.replace(" ",""));
        if (subjectEntity.getName() == null || subjectEntity.getName().trim().length() == 0) {
            Files.delete(Paths.get(filePath));
            return fail(null, "量表名称为空");
        }
        if (subjectEntity.getUploader() == null || subjectEntity.getUploader().trim().length() <= 0) {
            Files.delete(Paths.get(filePath));
            return fail(null, "请输入上传人信息");
        }

        if (this.subjectService.getSubjectByname(subjectEntity.getName()) != null) {
            Files.delete(Paths.get(filePath));
            return fail(null, "该量表已存在");
        }

        List<List<List<Object>>> datas = ExcelUtil.getBankListByExcelSheet(new FileInputStream(file.getAbsolutePath()), file.getName());
        //获取题目信息并入库
        List<List<Object>> sheet0 = datas.get(0);
        for (int i = 0; i < sheet0.size(); i++) {
            List<Object> scales = sheet0.get(i);
            if (scales.size() < 6){
                //删除量表题目信息
                this.scaleService.deleteScaleByFlag(flag);
                return fail("题目信息sheet页格式有误");
            }
            System.out.println(scales);
            ScaleEntity scaleEntity = new ScaleEntity();
            scaleEntity.setQuestionNo(scales.get(0).toString());
            scaleEntity.setSerialNo(scales.get(1).toString());
            //scaleEntity.setAnswer(DESede.encryptString(scales.get(2).toString()));
            //scaleEntity.setCheckItems(DESede.encryptString(scales.get(3).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);
//            }
//
//            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 if (questionType.equals("单选")) {
                scaleEntity.setQuestionType(Constant.MAGIC_NUM_0);
            } else if (questionType.equals("单选，填空")) {
                scaleEntity.setQuestionType(Constant.MAGIC_NUM_02);
            } else if (questionType.equals("多选，填空")) {
                scaleEntity.setQuestionType(Constant.MAGIC_NUM_12);
            }
            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);
            System.out.println(scaleEntity.toString());
            this.scaleService.saveScale(scaleEntity);
        }
        //获取答案计分规则信息并入库
        List<List<Object>> sheet1 = datas.get(1);
        for (int i = 0; i < sheet1.size(); i++) {
            List<Object> answers = sheet1.get(i);
            if (answers.size() < 3){
                //删除量表计分规则信息
                this.answerService.deleteAnswerByFlag(flag);
                return fail("计分规则sheet页格式有误");
            }
            String[] questions = answers.get(0).toString().split("；");
            for (int y = 0; y < questions.length; y++) {
                AnswerEntity answerEntity = new AnswerEntity();
                answerEntity.setFlag(flag);
                answerEntity.setQuestionNo(questions[y]);
                //answerEntity.setName(DESede.encryptString(answers.get(1).toString()));
                answerEntity.setName(answers.get(1).toString());
                answerEntity.setOptions("");
                answerEntity.setQuestionType("0");
                //answerEntity.setScore(DESede.encryptString(answers.get(2).toString()));
                answerEntity.setScore(answers.get(2).toString());
                //answerEntity.setScoreDirection("1");
                this.answerService.saveAnswer(answerEntity);
            }

        }
        //获取判断标准信息并入库
        List<List<Object>> sheet2 = datas.get(2);
        for (int i = 0; i < sheet2.size(); i++) {
            List<Object> scaleMarks = sheet2.get(i);
            if (scaleMarks.size() < 5){
                //删除量表判断标准信息
                this.scaleMarksService.deleteScaleMarkByFlag(flag);
                return fail("判断标准sheet页格式有误");
            }
            ScaleMarksEntity scaleMarksEntity = new ScaleMarksEntity();
            scaleMarksEntity.setFlag(flag);
            /*scaleMarksEntity.setName(DESede.encryptString(scaleMarks.get(0).toString()));
            scaleMarksEntity.setImprovementSuggestions(DESede.encryptString(scaleMarks.get(4).toString()));
            scaleMarksEntity.setSymptom(DESede.encryptString(scaleMarks.get(3).toString()));
            scaleMarksEntity.setScoreEnd(DESede.encryptString(scaleMarks.get(2).toString()));
            scaleMarksEntity.setScoreStart(DESede.encryptString(scaleMarks.get(1).toString()));*/
            scaleMarksEntity.setName(scaleMarks.get(0).toString());
            scaleMarksEntity.setImprovementSuggestions(scaleMarks.get(4).toString());
            scaleMarksEntity.setSymptom(scaleMarks.get(3).toString());
            scaleMarksEntity.setScoreEnd(scaleMarks.get(2).toString());
            scaleMarksEntity.setScoreStart(scaleMarks.get(1).toString());
            scaleMarksEntity.setIsTotalScoreExplain("否");
            scaleMarksEntity.setNameExplain("ABrm0oUKl4k");
            scaleMarksEntity.setReference("ABrm0oUKl4k");
            scaleMarksEntity.setStandardDeviation("ABrm0oUKl4k");
            scaleMarksEntity.setSuggestion("ABrm0oUKl4k");
            this.scaleMarksService.saveScaleMarks(scaleMarksEntity);

        }
        //获取维度信息并入库
        List<List<Object>> sheet3 = datas.get(3);
        for (int i = 0; i < sheet3.size(); i++) {
            List<Object> dimensions = sheet3.get(i);
            if (dimensions.size() < 2){
                //删除量表维度信息
                this.dimensionService.deleteDimensionByFlag(flag);
                return fail("维度信息sheet页格式有误");
            }
            DimensionEntity dimensionEntity = new DimensionEntity();
            dimensionEntity.setFlag(flag);
            //dimensionEntity.setName(DESede.encryptString(dimensions.get(0).toString()));
            //dimensionEntity.setQuestionNo(DESede.encryptString(dimensions.get(1).toString()));
            dimensionEntity.setName(dimensions.get(0).toString());
            dimensionEntity.setQuestionNo(dimensions.get(1).toString());
            this.dimensionService.saveDimension(dimensionEntity);
        }
        subjectEntity.setFileName(filePath);
        this.subjectService.save(subjectEntity);
        CategorySubjectEntity categorySubjectEntity = new CategorySubjectEntity();
        categorySubjectEntity.setFlag(flag);
        categorySubjectEntity.setEname("TC");
        this.categorySubjectService.save(categorySubjectEntity);
        InstitutionAuthEntity institutionAuthEntity = new InstitutionAuthEntity();
        institutionAuthEntity.setInstitutionNo(institutionNo);
        institutionAuthEntity.setType("0");
        institutionAuthEntity.setBId(this.subjectService.getSubjectEntityByFlag(flag).getId());
        List<InstitutionAuthEntity> institutionAuthEntities = new ArrayList<>();
        institutionAuthEntities.add(institutionAuthEntity);
        this.institutionAuthService.saveInstitutionAuthList(institutionAuthEntities);
        GroupAuthEntity groupAuthEntity = new GroupAuthEntity();
        //根据机构编号查询默认分组id
        groupAuthEntity.setBId(this.subjectService.getSubjectEntityByFlag(flag).getId());
        groupAuthEntity.setType("0");
        groupAuthEntity.setGroupId(this.groupInfoService.findGroupByInstitutionNoAndName(institutionNo,"默认分组").getId());
        this.groupAuthService.addGroupAuth(groupAuthEntity);
        System.out.println(datas);
        return success();
    }

    /**
     * 量表上传需要接口
     * 导入量表
     * 1、量表名称  2、量表指导语  3、量表录入人
     * @return
     */
    @PostMapping("subjectInfoUpload/importTest")
    @ApiOperation(value = "量表导入测试")
    public Result importScale(String scaleName, String scaleDesc, String uploader, String eName, String scoringPrinciple, String currentLimit, String scaleCate,String people , 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);
        subjectEntity.setScaleLimit(currentLimit);
        if(people.contains("0")){
            people = "0";
        }
        subjectEntity.setMen(people.replace(" ",""));
        if (subjectEntity.getName() == null || subjectEntity.getName().trim().length() == 0) {
            return fail(null, "量表名称为空");
        }
        if (subjectEntity.getUploader() == null || subjectEntity.getUploader().trim().length() <= 0) {
            return fail(null, "请输入上传人信息");
        }

        if (this.subjectService.getSubjectByname(subjectEntity.getName()) != null) {
            return fail(null, "该量表已存在");
        }
        List<List<List<Object>>> datas = ExcelUtil.getBankListByExcelSheet(file.getInputStream(), file.getOriginalFilename());
        //获取题目信息并入库
        List<List<Object>> sheet0 = datas.get(0);
        for (int i = 0; i < sheet0.size(); i++) {
            List<Object> scales = sheet0.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);
//            }
//
//            String questionType = scales.get(4).toString();
            if (questionType.equals("单选")) {
                scaleEntity.setQuestionType(Constant.MAGIC_NUM_0);
            } else if (questionType.equals("多选")) {
                scaleEntity.setQuestionType(Constant.MAGIC_NUM_1);
            } else if (questionType.equals("文本")) {
                scaleEntity.setQuestionType(Constant.MAGIC_NUM_2);
            } else if (questionType.equals("数字")) {
                scaleEntity.setQuestionType(Constant.MAGIC_NUM_3);
            } else if (questionType.equals("日期")) {
                scaleEntity.setQuestionType(Constant.MAGIC_NUM_4);
            }else if (questionType.equals("下拉选")) {
                scaleEntity.setQuestionType(Constant.MAGIC_NUM_5);
            } else if (questionType.equals("跳转单选")) {
                scaleEntity.setQuestionType(Constant.MAGIC_NUM_6);
            } else if (questionType.equals("说明单选")) {
                scaleEntity.setQuestionType(Constant.MAGIC_NUM_7);
            } else if (questionType.equals("附图单选")) {
                scaleEntity.setQuestionType(Constant.MAGIC_NUM_8);
            }else if (questionType.equals("附图多选")) {
                scaleEntity.setQuestionType(Constant.MAGIC_NUM_9);
            } else if (questionType.equals("附说明单选")) {
                scaleEntity.setQuestionType(Constant.MAGIC_NUM_10);
            } else if (questionType.equals("附说明多选")) {
                scaleEntity.setQuestionType(Constant.MAGIC_NUM_11);
            }
            scaleEntity.setWeight("");
            String scoreDirection = scales.get(5).toString();
            if (scoreDirection.equals("正向")) {
                scoreDirection = Constant.MAGIC_NUM_1;
            } else if (scoreDirection.equals("反向")) {
                scoreDirection = Constant.MAGIC_NUM_0;
            }
            scaleEntity.setScoreDirection(scoreDirection);
//            量表模板不提供分值
            scaleEntity.setScore("");
            scaleEntity.setFlag(flag);
            System.out.println(scaleEntity.toString());
            this.scaleService.saveScale(scaleEntity);
        }
        //获取答案计分规则信息并入库
        List<List<Object>> sheet1 = datas.get(1);
        for (int i = 0; i < sheet1.size(); i++) {
            List<Object> answers = sheet1.get(i);
            String[] questions = answers.get(0).toString().split("；");
            for (int y = 0; y < questions.length; y++) {
                AnswerEntity answerEntity = new AnswerEntity();
                answerEntity.setFlag(flag);
                answerEntity.setQuestionNo(questions[y]);
                answerEntity.setName(answers.get(1).toString());
                answerEntity.setOptions("");
                answerEntity.setQuestionType("0");
                answerEntity.setScore(answers.get(2).toString());
                //answerEntity.setScoreDirection("1");
                this.answerService.saveAnswer(answerEntity);
            }

        }
        //获取评分规则信息并入库
        List<List<Object>> sheet2 = datas.get(2);
        for (int i = 0; i < sheet2.size(); i++) {
            List<Object> scaleMarks = sheet2.get(i);
            ScaleMarksEntity scaleMarksEntity = new ScaleMarksEntity();
            scaleMarksEntity.setFlag(flag);
            scaleMarksEntity.setName(scaleMarks.get(0).toString());
            scaleMarksEntity.setImprovementSuggestions(scaleMarks.get(4).toString());
            scaleMarksEntity.setSymptom(scaleMarks.get(3).toString());
            scaleMarksEntity.setScoreEnd(scaleMarks.get(2).toString());
            scaleMarksEntity.setScoreStart(scaleMarks.get(1).toString());
            this.scaleMarksService.saveScaleMarks(scaleMarksEntity);

        }
        //获取维度信息并入库
        List<List<Object>> sheet3 = datas.get(3);
        for (int i = 0; i < sheet3.size(); i++) {
            List<Object> dimensions = sheet3.get(i);
            DimensionEntity dimensionEntity = new DimensionEntity();
            dimensionEntity.setFlag(flag);
            dimensionEntity.setName(dimensions.get(0).toString());
            dimensionEntity.setQuestionNo(dimensions.get(1).toString());
            this.dimensionService.saveDimension(dimensionEntity);
        }

        //文件保存
        String fileName = "";
        String FILEDIR;

        if (OSUtil.isLinux()) {
            FILEDIR = "./scales/";
        } else {
            FILEDIR = "./psychological/scales/";
        }
        if (file == null) {
            throw new Exception("文件为空");
        } else {
            String suffix = file.getOriginalFilename();

            if (!file.isEmpty()) {
                fileName = suffix;
                subjectEntity.setFileName(fileName);
                try {
                    File temp = new File(FILEDIR);
                    if (!temp.exists()) {
                        temp.mkdirs();
                    }
                    System.out.println("FILEDIR---" + FILEDIR);
                    System.out.println("fileName--" + fileName);
                    File fileLocal = new File(FILEDIR, fileName);
                    FileUtils.copyInputStreamToFile(file.getInputStream(), fileLocal);
                } catch (Exception e) {
                    message = message + "文件上传失败";
                    e.printStackTrace();
                }
            }
        }
        this.subjectService.save(subjectEntity);
        CategorySubjectEntity categorySubjectEntity = new CategorySubjectEntity();
        categorySubjectEntity.setFlag(flag);
        categorySubjectEntity.setEname(scaleCate);
        this.categorySubjectService.save(categorySubjectEntity);
        System.out.println(datas);
        return success();
    }

    @PostMapping("importNewScale")
    @ApiOperation(value = "修改量表数据格式")
    public Result importNewScale(String flag, MultipartFile file ) throws Exception {
        if(file == null){
            return fail("文件为空");
        }
        String message = "提交成功";

        List<List<List<Object>>> datas = ExcelUtil.getBankListByExcelSheet(file.getInputStream(), file.getOriginalFilename());
        /*//获取题目信息并入库
        List<List<Object>> sheet0 = datas.get(0);
        for (int i = 0;i <sheet0.size();i++){
            List<Object> scales = sheet0.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);
            System.out.println(scaleEntity.toString());
            this.scaleService.saveScale(scaleEntity);
        }*/
        //获取答案计分规则信息并入库
        List<List<Object>> sheet1 = datas.get(1);
        for (int i = 0;i <sheet1.size();i++){
            List<Object> answers = sheet1.get(i);
            String[] questions = answers.get(0).toString().split("；");
            for (int y = 0;y<questions.length;y++) {
                AnswerEntity answerEntity = new AnswerEntity();
                answerEntity.setFlag(flag);
                answerEntity.setQuestionNo(questions[y]);
                answerEntity.setName(answers.get(1).toString());
                answerEntity.setOptions("");
                answerEntity.setQuestionType("0");
                answerEntity.setScore(answers.get(2).toString());
                //answerEntity.setScoreDirection("1");
                this.answerService.saveAnswer(answerEntity);
            }
        }
        //获取评分规则信息并入库
        List<List<Object>> sheet2 = datas.get(2);
        for (int i = 0;i <sheet2.size();i++){
            List<Object> scaleMarks = sheet2.get(i);
            ScaleMarksEntity scaleMarksEntity = new ScaleMarksEntity();
            scaleMarksEntity.setFlag(flag);
            scaleMarksEntity.setName(scaleMarks.get(0).toString());
            scaleMarksEntity.setImprovementSuggestions(scaleMarks.get(4).toString());
            scaleMarksEntity.setSymptom(scaleMarks.get(3).toString());
            scaleMarksEntity.setScoreEnd(scaleMarks.get(2).toString());
            scaleMarksEntity.setScoreStart(scaleMarks.get(1).toString());
            this.scaleMarksService.saveScaleMarks(scaleMarksEntity);

        }
        //获取维度信息并入库
        List<List<Object>> sheet3 = datas.get(3);
        for (int i = 0;i <sheet3.size();i++) {
            List<Object> dimensions = sheet3.get(i);
            DimensionEntity dimensionEntity = new DimensionEntity();
            dimensionEntity.setFlag(flag);
            dimensionEntity.setName(dimensions.get(0).toString());
            dimensionEntity.setQuestionNo(dimensions.get(1).toString());
            this.dimensionService.saveDimension(dimensionEntity);
        }

        return success();
    }


}
