package cn.com.countrygarden.bi.main.service.personnel.impl;
import cn.com.countrygarden.bi.main.model.PageData;
import cn.com.countrygarden.bi.main.model.dup.DupOrgan;
import cn.com.countrygarden.bi.main.model.test.Test;
import cn.com.countrygarden.bi.main.service.project.ProjectJointPlanService;
import cn.com.countrygarden.bi.main.service.review.commonService.ClassificationVoService;
import cn.com.countrygarden.bi.main.service.test.TestService;
import cn.com.countrygarden.bi.main.sms.SmsBaseManager;
import cn.com.countrygarden.bi.main.sms.SmsSend;
import cn.com.countrygarden.bi.main.util.provingMobileUtils;
import sun.security.rsa.RSAPadding;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import static org.hamcrest.CoreMatchers.nullValue;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.model.AccessToken;
import cn.com.countrygarden.bi.main.model.sys.Function;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.com.countrygarden.bi.main.model.personnel.Personnel;
import cn.com.countrygarden.bi.main.model.personnel.PersonnelAssessment;
import cn.com.countrygarden.bi.main.model.review.ReviewEvaluate;
import cn.com.countrygarden.bi.main.model.review.ReviewInvestigated;
import cn.com.countrygarden.bi.main.model.review.ReviewJudge;
import cn.com.countrygarden.bi.main.model.review.ReviewQuestionnaire;
import cn.com.countrygarden.bi.main.model.review.ReviewQuestionnaireProblem;
import cn.com.countrygarden.bi.main.model.review.ReviewQuestionnaireProblemClassification;
import cn.com.countrygarden.bi.main.model.review.ReviewQuestionnaireProblemOption;
import cn.com.countrygarden.bi.main.model.review.ReviewScore;
import cn.com.countrygarden.bi.main.dao.personnel.PersonnelAssessmentMapper;
import cn.com.countrygarden.bi.main.dao.personnel.PersonnelCampusevaluationMapper;
import cn.com.countrygarden.bi.main.dao.personnel.PersonnelMapper;
import cn.com.countrygarden.bi.main.dao.review.ReviewEvaluateMapper;
import cn.com.countrygarden.bi.main.dao.review.ReviewInvestigatedMapper;
import cn.com.countrygarden.bi.main.dao.review.ReviewJudgeMapper;
import cn.com.countrygarden.bi.main.dao.review.ReviewQuestionnaireMapper;
import cn.com.countrygarden.bi.main.dao.review.ReviewQuestionnaireProblemClassificationMapper;
import cn.com.countrygarden.bi.main.dao.review.ReviewQuestionnaireProblemMapper;
import cn.com.countrygarden.bi.main.dao.review.ReviewQuestionnaireProblemOptionMapper;
import cn.com.countrygarden.bi.main.dao.review.ReviewQuestionnaireProblemTypeMapper;
import cn.com.countrygarden.bi.main.dao.review.ReviewScoreMapper;
import cn.com.countrygarden.bi.main.dto.PersonInfoVO;
import cn.com.countrygarden.bi.main.dto.PersonnelAdvisorDTO;
import cn.com.countrygarden.bi.main.dto.PersonnelAssessmentDTO;
import cn.com.countrygarden.bi.main.dto.ProblemDetailDTO;
import cn.com.countrygarden.bi.main.dto.ReviewAnswerBeforeVo;
import cn.com.countrygarden.bi.main.dto.ReviewInvestigationVo;
import cn.com.countrygarden.bi.main.dto.ReviewQuestionnaireEditVo;
import cn.com.countrygarden.bi.main.dto.ReviewQuestionnaireProblemDTO;
import cn.com.countrygarden.bi.main.dto.ReviewQuestionnaireProblemEditVo;
import cn.com.countrygarden.bi.main.dto.ReviewQuestionnaireProblemOptionVo;
import cn.com.countrygarden.bi.main.dto.ReviewQuestionnaireProblemVo;
import cn.com.countrygarden.bi.main.dto.ReviewQuestionnairelistVo;
import cn.com.countrygarden.bi.main.dto.ReviewScoreDTO;
import cn.com.countrygarden.bi.main.dto.ReviewScoreProblemDTO;
import cn.com.countrygarden.bi.main.dto.ReviewScoreperassDTO;
import cn.com.countrygarden.bi.main.dto.TemplateParamVo;
import cn.com.countrygarden.bi.main.dto.canteenProblemDetaiDTO;
import cn.com.countrygarden.bi.main.dto.personnelTagDTO;
import cn.com.countrygarden.bi.main.dto.reviewInvestigatedIsRepeatVo;
import cn.com.countrygarden.bi.main.dto.ReviewExcel.ReviewRinquDTO;
import cn.com.countrygarden.bi.main.dto.ReviewExcel.ReviewjudgeGradeDTO;
import cn.com.countrygarden.bi.main.exception.ServiceException;
import cn.com.countrygarden.bi.main.service.personnel.ClassificationVo270Service;
import cn.com.countrygarden.bi.main.service.personnel.PersonnelAssessmentService;
import cn.com.countrygarden.bi.main.service.personnel.PersonnelCommenService;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example.Criteria;
import cn.com.countrygarden.bi.main.core.Response;

/**
 * 270评估-业务逻辑层实现
 *
 * @author 吕伟峰
 * @email www.justintoforest@gamail.com
 * @url 
 * @date 2018-10-08
 */
@Service
@Transactional
public class PersonnelAssessmentServiceImpl implements PersonnelAssessmentService{
	@Autowired
	private ClassificationVoService classificationVoService;
    @Autowired
    private PersonnelAssessmentMapper personnelAssessmentMapper;
    
    @Autowired
    private PersonnelCampusevaluationMapper personnelCampusevaluationMapper;
    
	@Autowired
	private ReviewQuestionnaireMapper reviewQuestionnaireMapper;
	
	@Autowired
	private ClassificationVo270Service classificationVo270Service;
	
	@Autowired
	private ReviewQuestionnaireProblemClassificationMapper reviewQuestionnaireProblemClassificationMapper;
	
	@Autowired
	private ReviewQuestionnaireProblemOptionMapper optionMapper;
	
	@Autowired
	private ReviewQuestionnaireProblemMapper reviewQuestionnaireProblemMapper;
	
	@Autowired
	private ReviewInvestigatedMapper reviewInvestigatedMapper;
	
	@Autowired
	private ReviewJudgeMapper reviewjudgemapper;
	
	@Autowired
	private ReviewScoreMapper reviewScoreMapper;
	
	@Autowired
    private ReviewEvaluateMapper reviewEvaluateMapper;
	
	@Autowired
	private PersonnelMapper personnelMapper;
	
	@Autowired
    private PersonnelCommenService personnelCommenService;

	private final Logger logger = LoggerFactory.getLogger(getClass());
	
    @Override
    public Result queryPageList(PersonnelAssessmentDTO personnelAssessment, int page, int size,AccessToken accessToken) {
    	
    	
//    	List<String> userIds= personnelCommenService.findRole(accessToken);
//		if(userIds!=null) {
//			if(userIds.size()==0||userIds.get(0).equals("-1")) {
//				//没有匹配的角色或没有查找到数据
//				return Response.response();
//			}		
//		}
    	Map<String, Object> rolesMap = personnelCommenService.findRoleInfoMap(accessToken.getUserCode());    	
    	
    	List<String> userquyu= new ArrayList<>();
		
    	List<DupOrgan> result=null;
    	for (Object obj : rolesMap.keySet()) {
    		String key = (String) obj;
    		if (key.equals("gj_admin")) {
    			 userquyu=null;
    			 rolesMap.put("identitys", null);
    			 break;
    		}else if (key.equals("role")) {
    			 return null;
			}else if (key.equals("gj_Area")) {
				rolesMap.put("identitys", null);
				
				 result = personnelCommenService.findDupCommByUserCode(accessToken.getUserCode(),null,true);
				for (int i = 0; i < result.size(); i++) {
					userquyu.add(result.get(i).getOrganName());
				}
			
			}
    		
    	}
    	
//    	List<PersonnelAssessmentDTO> dtoper=new ArrayList<PersonnelAssessmentDTO>();        
//      	if (result!=null&&result.size()!=0) {
//      		for (int i = 0; i < result.size(); i++) {
//      			List<PersonnelAssessmentDTO> persapper=personnelAssessmentMapper.pernnelAsseslidt(personnelAssessment,rolesMap,result.get(i).getOrganName());
//      			if (persapper.size()!=0) {
//      				dtoper.addAll(persapper);
//  				}    		
//      		}
//  		}else {
//  			dtoper = personnelAssessmentMapper.pernnelAsseslidt(personnelAssessment,rolesMap,null);
//  		}
    	
    	
    	List<ReviewInvestigated> revinveads=personnelAssessmentMapper.revinveads(personnelAssessment);
    	
    	
    	List<PersonnelAssessmentDTO> perslassntscore=new ArrayList<PersonnelAssessmentDTO>();
    	List<PersonnelAssessmentDTO> scprezong=new ArrayList<PersonnelAssessmentDTO>();
    	for (int i = 0; i < revinveads.size(); i++) {
    		perslassntscore.addAll(personnelAssessmentMapper.perslassntscore(revinveads.get(i).getId()));
    		scprezong.addAll(personnelAssessmentMapper.scprezong(revinveads.get(i).getId()));
		}
    	//用户   pe.name,pas.id,pe.user_id,rqc.name
    	if (personnelAssessment.getRegionName()!=null&&!personnelAssessment.getRegionName().equals("")&&personnelAssessment.getUserId()!=null&&!personnelAssessment.getUserId().equals("")
      			&&personnelAssessment.getName()!=null&&!personnelAssessment.getName().equals("")) {
      		
      		userquyu=null;
		}
    	List<PersonnelAssessmentDTO> pernnelslidt=personnelAssessmentMapper.pernnelAsseslidt(personnelAssessment,rolesMap,userquyu);      
    	
    	for (int i = 0; i < pernnelslidt.size(); i++) {
    		for (int j = 0; j < scprezong.size(); j++) {
    			if (pernnelslidt.get(i).getId().equals(scprezong.get(j).getId())) {
    				pernnelslidt.get(i).setScore(scprezong.get(j).getScore());
    			}
			}
			
		}
    	Page<Object> pageList = PageHelper.startPage(page, size);
    	List<PersonnelAssessmentDTO> pernnelAsseslidt=new ArrayList<PersonnelAssessmentDTO>(pernnelslidt);
    	//System.out.println(Response.response(pernnelAsseslidt)); 
//    	Set<PersonnelAssessmentDTO> pernslidt=new HashSet<>();
//    	for (int i = 0; i < pernnelAsseslidtset.size(); i++) {
//    		pernslidt.addAll(pernnelAsseslidtset);
//    	
//		}
//    	
    	
    	//List<PersonnelAssessmentDTO> pernnelAsseslidt=new ArrayList<>(pernslidt);     pernnelAsseslidtset 	
    
    	//问题分类
    	List<ReviewQuestionnaireProblemClassification> reviewreProblemClaions=personnelAssessmentMapper.reviewreProblemClaions();
    	String[] rqpcAry=new String[reviewreProblemClaions.size()];
    	for (int i = 0; i < reviewreProblemClaions.size(); i++) {
    		rqpcAry[i]=reviewreProblemClaions.get(i).getName();
		}
    	
//		构建列表数据
		List<PersonnelAssessmentDTO> personnelAssesDTOS=new ArrayList<PersonnelAssessmentDTO>();
		for (int i = 0; i < pernnelAsseslidt.size(); i++) {
			PersonnelAssessmentDTO peronnelaDTO=new PersonnelAssessmentDTO();
			peronnelaDTO.setId(pernnelAsseslidt.get(i).getId());
			peronnelaDTO.setUserId(pernnelAsseslidt.get(i).getUserId());
			peronnelaDTO.setName(pernnelAsseslidt.get(i).getName());
			peronnelaDTO.setRegionName(pernnelAsseslidt.get(i).getRegionName());
			peronnelaDTO.setEvaluation(pernnelAsseslidt.get(i).getEvaluation());
			peronnelaDTO.setPersonnelId(pernnelAsseslidt.get(i).getPersonnelId());
			peronnelaDTO.setScore(pernnelAsseslidt.get(i).getScore());
			peronnelaDTO.setQuestionnaireId(pernnelAsseslidt.get(i).getQuestionnaireId());
			peronnelaDTO.setInvestigatedId(pernnelAsseslidt.get(i).getInvestigatedId());
			peronnelaDTO.setCreatedBy(pernnelAsseslidt.get(i).getCreatedBy());
			peronnelaDTO.setCreatedName(pernnelAsseslidt.get(i).getCreatedName());
			peronnelaDTO.setCreatedDate(pernnelAsseslidt.get(i).getCreatedDate());
			List<String> list = new ArrayList<>(rqpcAry.length);
			for (int i1 = 0; i1 < rqpcAry.length; i1++) {
				list.add("0");
			}
			peronnelaDTO.setAvgsorce(list);
			personnelAssesDTOS.add(peronnelaDTO);
		}
		
		
//		组装数据
		DecimalFormat df=new DecimalFormat("######0.00");   
		for (PersonnelAssessmentDTO problemas : perslassntscore) {
			int qpcIndex=findAryIndex(problemas.getRqcname(),rqpcAry);
			if (qpcIndex==-1) {
				 continue;
			}
			int detailIndex=findDetailAryIndexas(String.valueOf(problemas.getInvestigatedId()),personnelAssesDTOS);
			if(detailIndex==-1) {
				 continue;
			}			
			PersonnelAssessmentDTO detailDTO = personnelAssesDTOS.get(detailIndex);
			
			if(problemas.getPngjun()!=0.0) {
				detailDTO.getAvgsorce().set(qpcIndex,df.format(problemas.getPngjun()));	
			}else {
				detailDTO.getAvgsorce().set(qpcIndex,"0");	
			}
				
			
		  }
				
		//Page<Object> pageList = PageHelper.startPage(page, size);
//		Set<PersonnelAssessmentDTO> setperass=new HashSet<PersonnelAssessmentDTO>();
//		for (int i = 0; i < personnelAssesDTOS.size(); i++) {
//			  for (int j = 0; j < personnelAssesDTOS.get(i).getAvgsorce().size(); j++) {
//				   if (StringUtils.isNotBlank(personnelAssesDTOS.get(i).getAvgsorce().get(j))) {
//					   setperass.add(personnelAssesDTOS.get(i));
//				}
//			}
//		}
	  	
		
    	//List<PersonnelAssessmentDTO> personelAsses=new ArrayList<PersonnelAssessmentDTO>(setperass);
         
    	
        PageData data=new PageData(pageList);
        data.setData(personnelAssesDTOS);
        JSONObject object=new JSONObject();
		 object.put("data",data);
		
		 object.put("rqc",rqpcAry);
		
        return Response.response(object);
    }
    
    private int findDetailAryIndexas(String id, List<PersonnelAssessmentDTO> problemas) {
		for (int i = 0; i < problemas.size(); i++) {
			if(String.valueOf(problemas.get(i).getInvestigatedId()).equalsIgnoreCase(id)){
				return i;
			}
		}
		return -1;
	}
    


    @Override
    public Result queryById(Integer id) {
        return Response.response(personnelAssessmentMapper.selectByPrimaryKey(id));
    }

    @Override
    public Result add(PersonnelAssessment personnelAssessment, AccessToken accessToken) {
    	personnelAssessment.setFlag(0);
    	personnelAssessment.setCreatedBy(accessToken.getUserCode());
        personnelAssessmentMapper.insertSelective(personnelAssessment);
        return Response.response();
    }

    @Override
    public Result edit(PersonnelAssessment personnelAssessment, AccessToken accessToken) {
    	personnelAssessment.setUpdatedBy(accessToken.getUserCode());
    	personnelAssessment.setUpdatedDate(new Date());
        personnelAssessmentMapper.updateByPrimary(personnelAssessment);
   
        return Response.response();
    }

    @Override
    public Result del(Integer id) {
        //int count = personnelAssessmentMapper.deleteByPrimaryKey(id);
    	int count = personnelAssessmentMapper.delupdate(id);
        return Response.response(count);
    }

	@Override
	public Result scoreproblem(ReviewScoreProblemDTO scoreproblem) {
		Page<Object> pageList = new Page<>();
		List<ReviewScoreProblemDTO> reviewScorDTO=personnelAssessmentMapper.scoreproblem(scoreproblem);
		PageData data = new PageData(pageList);
		//题目，分类
		List<ReviewQuestionnaireProblemDTO> questionnaireProblems=personnelAssessmentMapper.questionnaireProblems(scoreproblem);
		
		List<ReviewJudge> judges=personnelAssessmentMapper.reviewjudge(scoreproblem);
//		人员信息
		String[] judgeAry=new String[judges.size()];
		for (int i = 0; i < judges.size(); i++) {
			judgeAry[i]=judges.get(i).getName();
		}
		
//		构建列表数据
		List<ProblemDetailDTO> problemDetailDTOS=new ArrayList<>();
		for (int i = 0; i < questionnaireProblems.size(); i++) {
			  ProblemDetailDTO detail=new ProblemDetailDTO();
			  detail.setRgname(scoreproblem.getRgname());
				detail.setDescribedname(questionnaireProblems.get(i).getName());
				detail.setDescribed(questionnaireProblems.get(i).getQuestionnaireProblemClassificationId());
				detail.setQuestionnaireId(questionnaireProblems.get(i).getId()+"");
				detail.setTitleDescription(questionnaireProblems.get(i).getTitleDescription());
				List<String> list = new ArrayList<>(judgeAry.length);
				for (int i1 = 0; i1 < judgeAry.length; i1++) {
					list.add("");
				}
				detail.setAnswer(list);
				problemDetailDTOS.add(detail);
		}
//		组装数据
		for (ReviewScoreProblemDTO problem : reviewScorDTO) {
			int judgeIndex=findAryIndex(problem.getName(),judgeAry);
			int detailIndex=findDetailAryIndex(problem.getQuestionnaireId(),problemDetailDTOS);
			ProblemDetailDTO detailDTO = problemDetailDTOS.get(detailIndex);
			if(StringUtils.isNotBlank(problem.getDanxu()))
				detailDTO.getAnswer().set(judgeIndex,problem.getDanxu());
			if(problem.getScore()!=null)
				detailDTO.getAnswer().set(judgeIndex,problem.getScore()+"");
			if(StringUtils.isNotBlank(problem.getAnswer()))
			detailDTO.getAnswer().set(judgeIndex,problem.getAnswer());
		}

		data.setData(problemDetailDTOS);
		JSONObject object=new JSONObject();
		object.put("data",data);
		object.put("judges",judgeAry);
		return Response.response(object);
						
	}
	
	private int findDetailAryIndex(String id, List<ProblemDetailDTO> problemDetailDTOS) {
		for (int i = 0; i < problemDetailDTOS.size(); i++) {
			if(problemDetailDTOS.get(i).getQuestionnaireId().equalsIgnoreCase(id)){
				return i;
			}
		}
		return -1;
	}


	public int findAryIndex(String name,String[] ary){
		for (int i = 0; i < ary.length; i++) {
			if(ary[i].equalsIgnoreCase(name)){
				return i;
			}
		}
		return -1;
	}

	@Override
	public Result ReviewQuestionnairelistVo(Integer id,String name,boolean hasRole,int page, int size, String userCode,
			Integer investigationmanagementId) {
		Page<Object> pageList = PageHelper.startPage(page, size);
		List<ReviewQuestionnairelistVo> reviewQuestionnairelistVo = personnelAssessmentMapper
				.ReviewQuestionnairelistVo(id,name,hasRole,userCode,investigationmanagementId);

		PageData data = new PageData(pageList);
		data.setData(pageList.getResult());
		return Response.response(data);
	}
	
	// 编辑问题前返回的数据
	public Result queryQuestionnaireAndproblem(int id) {
 
		
		ReviewQuestionnaireProblemEditVo questionnaireProblemEditVo = new ReviewQuestionnaireProblemEditVo();
		ReviewQuestionnaire reviewQuestionnaire = reviewQuestionnaireMapper.selectByPrimaryKey(id);
		questionnaireProblemEditVo.setQuestionnaireId(id);
		questionnaireProblemEditVo.setInvestigationmanagementId(reviewQuestionnaire.getInvestigationmanagementId());
		questionnaireProblemEditVo.setQuestionnaireName(reviewQuestionnaire.getName());
		questionnaireProblemEditVo.setClassificationEditIds(classificationVo270Service.ClassificationFlagYesEdit(id));
		questionnaireProblemEditVo.setQuestionnaireDescribed(reviewQuestionnaire.getDescribed());
		questionnaireProblemEditVo.setCreateBy(reviewQuestionnaire.getCreateBy());
		questionnaireProblemEditVo.setCreateTime(reviewQuestionnaire.getCreateTime());
		//questionAry
		questionnaireProblemEditVo.setQtypeAry(personnelAssessmentMapper.selectQuestionnaireProblemTypeVo(reviewQuestionnaire.getInvestigationmanagementId()));
		questionnaireProblemEditVo.setQuestionAry(personnelAssessmentMapper.queryQuestionnaireProblemdanVo(id));
		questionnaireProblemEditVo.setQclassAry(
				personnelAssessmentMapper.queryQuestionnaireProblemClassificationVo(reviewQuestionnaire.getInvestigationmanagementId()));
		return Response.response(questionnaireProblemEditVo);
	}
	
	// 添加问题前先返回问题分类列表与题型列表
		public Result queryProblemTypeAndProblemClass(int investigationmanagementId) {
			ReviewQuestionnaireProblemEditVo typeAndClassList = new ReviewQuestionnaireProblemEditVo();
			typeAndClassList.setQtypeAry(personnelAssessmentMapper.selectQuestionnaireProblemTypeVo(investigationmanagementId));
			typeAndClassList.setQclassAry(
					personnelAssessmentMapper.queryQuestionnaireProblemClassificationVo(investigationmanagementId));

			return Response.response(typeAndClassList);
		}

		@Override
		public Result addAssessment(ReviewQuestionnaire reviewQuestionnaire, String str, String qclassAryNew,
				AccessToken accessToken) {
			if(reviewQuestionnaire.getInvestigationmanagementId()==null) {
	        	reviewQuestionnaire.setId(1);//添加270评测问卷
	        }
			// 处理问题分类
			JSONArray qclassAry = (JSONArray) JSON.parseArray(qclassAryNew);
			ReviewQuestionnaireProblemClassification classification = null;
			List<Integer> classificationId = new ArrayList<Integer>();
			LinkedList<ReviewQuestionnaireProblemClassification> classificationList = new LinkedList<>();
			// 存放Flag为2的classficationId
			List<Integer> classificationFlagId = new ArrayList<Integer>();

			for (int i = 0; i < qclassAry.size(); i++) {
				classification = new ReviewQuestionnaireProblemClassification();
				JSONObject classificationObj = qclassAry.getJSONObject(i);

				// 如果两个相等则为新增问题分类
				if (classificationObj.getString("id").equals(classificationObj.getString("label"))) {
					classification.setName(classificationObj.getString("label"));
					classification.setCreateBy(accessToken.getUserCode());
					classification.setFlag(1);
					classification.setInvestigationmanagementId(reviewQuestionnaire.getInvestigationmanagementId());
					classificationList.add(classification);

				} else {
					// 否则为数据库已经存在的数据，除了数据库已经存在的数据其他都进行删除
					classificationId.add(classificationObj.getInteger("id"));

				}

			}

			// 添加问题分类前除了没有被用户删除的问题分类其他全部进行删除
			if (classificationId.size() != 0) {
				personnelAssessmentMapper.deleteNotClassificationIds(classificationId);
			}

			// 添加问题分类
			if (classificationList.size() != 0) {
				if (reviewQuestionnaireProblemClassificationMapper.insertList(classificationList) <= 0) {
					throw new ServiceException("ReviewQuestionnaireProblemService异常");
				}
			}
			boolean sign = true;
			breakStr:

			// 插入问卷表
			if (reviewQuestionnaire != null && str != null && str != "") {

				reviewQuestionnaire.setCreateBy(accessToken.getUserCode());
				if (reviewQuestionnaireMapper.insertSelective(reviewQuestionnaire) > 0) {

					String param = "[" + str + "]";
					JSONArray ary = (JSONArray) JSON.parseArray(param);
					ReviewQuestionnaireProblem problems = null;
					// 插入问题表
					for (int i = 0; i < ary.size(); i++) {
						JSONObject obj = ary.getJSONObject(i);
						problems = new ReviewQuestionnaireProblem();
						problems.setQuestionnaireId(reviewQuestionnaire.getId());

						// 判断classification是否是新增的问题分类 && classificationList.size() > 0
						
						if (!obj.getString("classification").equals("")) {
							boolean flag = true;
							for (ReviewQuestionnaireProblemClassification classificatio : classificationList) {
								String strReplace=(obj.getString("classification")).replace(" ","");
								String classificatioName=(classificatio.getName()).replace(" ","");
								if (classificatioName.equals(strReplace)) {
									problems.setQuestionnaireProblemClassificationId(classificatio.getId());
									flag = false;
									break;
								}
							}
							if (flag) {
								problems.setQuestionnaireProblemClassificationId(obj.getInteger("classification"));
							}
						} else {
							List<Integer> classificationid=personnelAssessmentMapper.selectrqclassiid();
								
								problems.setQuestionnaireProblemClassificationId(classificationid.get(0));
							
						}

						// 当问题分类被问卷使用后改变状态flag为不能再被删除
						classificationFlagId.add(problems.getQuestionnaireProblemClassificationId());
						problems.setQuestionTypeId(obj.getInteger("type"));
						if (obj.getInteger("type") == 1) {
							if (obj.getInteger("score") > 0) {
								problems.setScore(obj.getInteger("score"));
							} else {
								sign = false;
								break breakStr;
							}
						}
						problems.setAnswerDescription(obj.getString("answerDescription"));
						problems.setTitleDescription(obj.getString("title").trim());
						problems.setCreateBy(accessToken.getUserCode());
						ReviewQuestionnaireProblemOption option = null;
						int count = reviewQuestionnaireProblemMapper.insertSelective(problems);
						JSONArray aryOption = (JSONArray) JSON.parseArray(obj.getString("option"));
						if (count > 0) {
							// 插入单选表
							for (int j = 0; j < aryOption.size(); j++) {
								JSONObject objOption = aryOption.getJSONObject(j);
								option = new ReviewQuestionnaireProblemOption();
								if (objOption.getString("name") != null && objOption.getString("name") != "") {
									option.setQuestionnaireProblemId(problems.getId());
									option.setName(objOption.getString("name"));
									option.setOptionScore(objOption.getInteger("optionScore"));
									option.setCreateBy(accessToken.getUserCode());
									if (optionMapper.insertSelective(option) <= 0) {
										sign = false;
										break breakStr;
									}
								}

							}
						} else {
							sign = false;
							break breakStr;
						}
					}
				} else {
					sign = false;
					break breakStr;
				}
			}

			if (!sign) {
				throw new ServiceException("ReviewQuestionnaireProblemService异常");
			}
			// 被当前问卷使用的更改问卷分类id状态
			classificationVo270Service.ClassificationFlag(classificationFlagId);
			
			return Response.response();
		}

		@Override
		public Result questionnaireParamVoOne(Integer id) {
			//删除问卷的同时更改问题分类flag的状态
			classificationVo270Service.ClassificationFlagUpdateService(id);
			
			// 根据问卷ID更改问卷状态为0
			ReviewQuestionnaire reviewQuestionnaire = new ReviewQuestionnaire();
			reviewQuestionnaire.setId(id);
			reviewQuestionnaire.setFlag(0);
			// 如果更改成功再根据问卷ID更改问题状态为0
			if (reviewQuestionnaireMapper.updateByPrimaryKeySelective(reviewQuestionnaire) > 0) {
				personnelAssessmentMapper.updateProblemFlag(id);
			}
			return Response.response();
		}

		@Override
		public Result editAssessment(ReviewQuestionnaireEditVo reviewQuestionnaireEditVo, String str,
				String qclassAryNew, AccessToken accessToken) throws ParseException {
			// 处理问题分类
			JSONArray qclassAry = (JSONArray) JSON.parseArray(qclassAryNew);
			ReviewQuestionnaireProblemClassification classification = null;
			List<Integer> classificationId = new ArrayList<Integer>();
			LinkedList<ReviewQuestionnaireProblemClassification> classificationList = new LinkedList<>();

			// 存放被当前问卷使用的问题分类id
			List<Integer> problemClassificationIds = new ArrayList<Integer>();

			for (int i = 0; i < qclassAry.size(); i++) {
				classification = new ReviewQuestionnaireProblemClassification();
				JSONObject classificationObj = qclassAry.getJSONObject(i);

				// 如果两个相等则为新增问题分类
				if (classificationObj.getString("id").equals(classificationObj.getString("label"))) {
					classification.setName(classificationObj.getString("label"));
					classification.setCreateBy(accessToken.getUserCode());
					classification.setFlag(1);
					classification.setInvestigationmanagementId(reviewQuestionnaireEditVo.getInvestigationmanagementId());
				
					classificationList.add(classification);

				} else {
					// 否则为数据库已经存在的数据，除了数据库已经存在的数据其他都进行删除
					classificationId.add(classificationObj.getInteger("id"));

				}
			}
			// 添加问题分类前除了没有被用户删除的问题分类其他全部进行删除
			if (classificationId.size() != 0) {
				classificationVo270Service.ClassificationFlagUpdateService(reviewQuestionnaireEditVo.getId());
				reviewQuestionnaireProblemClassificationMapper.deleteNotClassificationIds(classificationId);
			}

			// 添加问题分类
			if (classificationList.size() != 0) {
				if (reviewQuestionnaireProblemClassificationMapper.insertList(classificationList) <= 0) {
					throw new ServiceException("ReviewQuestionnaireProblemService异常");
				}
			}

			boolean sign = true;
			breakStr:

			if (reviewQuestionnaireEditVo != null && str != null && str != "") {
				// 根据问卷ID得到问题ID集合
				List<Integer> problemId = reviewQuestionnaireProblemMapper
						.selectProblemId(reviewQuestionnaireEditVo.getId());
				// 根据问题ID集合批量删除单选项
				if (problemId.size() != 0) {
					optionMapper.deleteproblemIds(problemId);
				}
				// 根据问卷ID删除问题
				if (reviewQuestionnaireProblemMapper.deleteQuestionnaireProblem(reviewQuestionnaireEditVo.getId()) > 0) {
					// 更新问卷ID
					ReviewQuestionnaire reviewQuestionnaire = new ReviewQuestionnaire();
					reviewQuestionnaire.setId(reviewQuestionnaireEditVo.getId());
					SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					reviewQuestionnaire.setName(reviewQuestionnaireEditVo.getQuestionnaireName());
					reviewQuestionnaire.setDescribed(reviewQuestionnaireEditVo.getQuestionnaireDescribed());
					reviewQuestionnaire.setCreateBy(reviewQuestionnaireEditVo.getCreateBy());
					reviewQuestionnaire.setCreateTime(dateFormat.parse(reviewQuestionnaireEditVo.getCreateTime()));
					reviewQuestionnaire.setUpdateBy(accessToken.getUserCode());
					reviewQuestionnaire.setUpdateTime(new Date());
					if (reviewQuestionnaireMapper.updateByPrimaryKeySelective(reviewQuestionnaire) > 0) {
						// 添加问题
						ReviewQuestionnaireProblem problem = new ReviewQuestionnaireProblem();
						String questionnaireProblems = "[" + str + "]";
						JSONArray ary = (JSONArray) JSON.parseArray(questionnaireProblems);
						for (int i = 0; i < ary.size(); i++) {
							problem = new ReviewQuestionnaireProblem();
							JSONObject obj = ary.getJSONObject(i);
							problem.setQuestionnaireId(reviewQuestionnaire.getId());
							// problem.setQuestionnaireProblemClassificationId(obj.getInteger("classification"));
							// 判断classification是否是新增的问题分类
							if (!obj.getString("classification").equals("")) {
								boolean flag = true;
								for (ReviewQuestionnaireProblemClassification classificatio : classificationList) {
									String strReplace=(obj.getString("classification")).replace(" ","");
									String classificatioName=(classificatio.getName()).replace(" ","");
									if (classificatioName.equals(strReplace)) {
							//		if (classificatio.getName().equals(obj.getString("classification"))) {
									problem.setQuestionnaireProblemClassificationId(classificatio.getId());
										flag = false;
										break;
									}

								}

								if (flag) {
									problem.setQuestionnaireProblemClassificationId(obj.getInteger("classification"));
								}
							} else {
								List<Integer> classificationid=reviewQuestionnaireProblemMapper.selectrqclassiid();
								
								problem.setQuestionnaireProblemClassificationId(classificationid.get(0));							
								//problem.setQuestionnaireProblemClassificationId(obj.getInteger("classification"));
							}
							// 当问题分类被问卷使用后需要改变状态flag为不能再被删除
							problemClassificationIds.add(problem.getQuestionnaireProblemClassificationId());

							problem.setQuestionTypeId(obj.getInteger("type"));
							problem.setTitleDescription(obj.getString("title"));
							if (obj.getInteger("type") == 1) {
								if (obj.getInteger("score") > 0) {
									problem.setScore(obj.getInteger("score"));
								} else {
									// 当分数不大于0时
									sign = false;
									break breakStr;
								}
							}
							problem.setAnswerDescription(obj.getString("answerDescription"));
							// 如果在编辑时问题是新增的则创建人为编辑人，否则创建人不变
							if (obj.getString("id") != null && obj.getString("id") != "") {
								problem.setId(obj.getInteger("id"));
								problem.setCreateBy(reviewQuestionnaireEditVo.getCreateBy());

								problem.setCreateTime(dateFormat.parse(reviewQuestionnaireEditVo.getCreateTime()));
								problem.setUpdateBy(accessToken.getUserCode());
								problem.setUpdateTime(new Date());
							} else {
								problem.setCreateBy(accessToken.getUserCode());
								problem.setCreateTime(new Date());
							}
							// 添加问题成功后再添加单选项
							if (reviewQuestionnaireProblemMapper.insertSelective(problem) > 0) {
								ReviewQuestionnaireProblemOption option = new ReviewQuestionnaireProblemOption();
								JSONArray aryOption = (JSONArray) JSON.parseArray(obj.getString("option"));
								// 插入单选表
								for (int j = 0; j < aryOption.size(); j++) {
									JSONObject objOption = aryOption.getJSONObject(j);
									option = new ReviewQuestionnaireProblemOption();
									if (objOption.getString("name") != null && objOption.getString("name") != "") {
										option.setQuestionnaireProblemId(problem.getId());
										option.setName(objOption.getString("name"));
										option.setOptionScore(Integer.parseInt(objOption.getString("optionScore").trim()));
										// 如果在编辑单选时problemId为null则创建人为编辑人，否则创建人不变
										if (objOption.getString("problemId") != null && objOption.getString("id") != "") {
											// option.setId(objOption.getInteger("problemId"));
											option.setCreateBy(reviewQuestionnaireEditVo.getCreateBy());

											option.setCreateTime(
													dateFormat.parse(reviewQuestionnaireEditVo.getCreateTime()));
											option.setUpdateBy(accessToken.getUserCode());
											option.setUpdateTime(new Date());
										} else {
											option.setCreateBy(accessToken.getUserCode());
											option.setCreateTime(new Date());
										}
										if (optionMapper.insertSelective(option) <= 0) {
											// 添加单选项
											sign = false;
											break breakStr;
										}
									}
								}

							} else {
								// 添加问题
								sign = false;
								break breakStr;
							}
						}

					} else {
						// 更新问卷
						sign = false;
						break breakStr;
					}
				} else {
					// 删除问题
					sign = false;
					break breakStr;
				}
			}

			// 更改被当前问卷使用后的问题分类状态
			classificationVo270Service.ClassificationFlag(problemClassificationIds);

			if (!sign) {
				throw new ServiceException("ReviewQuestionnaireProblemService异常");
			}

			return Response.response();
		}
		
		@Autowired
		SmsSend smsSend;

		@Override
		public Result appAssessment(ReviewInvestigated reviewInvestigated, String upJsonStr, String sameJsonStr,
				String downJsonStr, AccessToken accessToken) {
			
			List<PersonInfoVO> personInfoCodeOrI=personnelAssessmentMapper.personInfoCodeOrId(reviewInvestigated.getJobNumber());
			
				//List<PersonnelAssessment> peradsssone=personnelAssessmentMapper.peradsssone(reviewInvestigated.getJobNumber());
				PersonnelAssessment peressment=null;
				//if (peradsssone.size()>0) {
					// peressment=new PersonnelAssessment();
					// peressment.setPersonnelId(personInfoCodeOrI.get(0).getId());	
					//personnelAssessmentMapper.deleteass(peressment);
				//}
				 peressment=new PersonnelAssessment();
				peressment.setPersonnelId(personInfoCodeOrI.get(0).getId());
				peressment.setCreatedName(reviewInvestigated.getCreatedName());
				peressment.setCreatedBy(accessToken.getUserCode());
				peressment.setCreatedDate(new Date());
				personnelAssessmentMapper.insertSelective(peressment);
			
				reviewInvestigated.setPersonnelassessmentId(peressment.getId());
			reviewInvestigated.setCreateBy(accessToken.getUserCode());
			ReviewQuestionnaire questionnaire = reviewQuestionnaireMapper
					.selectByPrimaryKey(reviewInvestigated.getQuestionnaireId());
			int i = reviewInvestigatedMapper.insertSelective(reviewInvestigated);
			if (i == 0) {
				throw new ServiceException();
			}
			ReviewJudge review;
			// 发送短信
			// 1.获得评选人姓名，被评选人姓名，被评选人电话
			TemplateParamVo templateParam = null;
			List<TemplateParamVo> templateParamVolist = new ArrayList<TemplateParamVo>();

			if (StringUtils.isNotBlank(upJsonStr)) {
				JSONObject jsonObjectup = JSONObject.parseObject(upJsonStr);
				JSONArray reviewers = jsonObjectup.getJSONArray("reviewers");

				for (Object object : reviewers) {
					review = new ReviewJudge();
					review.setInvestigatedId(reviewInvestigated.getId());
					review.setQuestionnaireId(reviewInvestigated.getQuestionnaireId());
					review.setGradeId(Integer.parseInt(jsonObjectup.getString("id")));
					review.setIssubmission(0);
					review.setIsPartake(0);
					review.setFlag(0);
					review.setCreateBy(accessToken.getUserCode());
					JSONObject jo =(JSONObject) object;
					String name = jo.getString("name");
					String tel = jo.getString("phone");
					if (name != null && !name.equals("") && tel != null && !tel.equals("")) {
						review.setName(name);
						review.setTel(tel);

						reviewjudgemapper.insertSelective(review);

						// 获得评选人姓名as_user，被评选人姓名,url到templateParam
						if (provingMobileUtils.isMobile(tel)) {

							templateParam = new TemplateParamVo();

							StringBuffer str = new StringBuffer("亲爱的" + review.getName() + "，您有一份关于"
									+ reviewInvestigated.getName() + "-" + questionnaire.getName()
									+ "的调查问卷，请点击链接参与评价："+SmsBaseManager.getAppPersonUrl()+"?id="
									+ reviewInvestigated.getId() + "&jd=" + review.getId() + "&qd="
									+ review.getQuestionnaireId() + " 退订回复TD");
							templateParam.setUrl(str.toString());
							templateParam.setPhone(tel);
							templateParamVolist.add(templateParam);
						}
					}

				}

			}

			if (StringUtils.isNotBlank(sameJsonStr)) {
				JSONObject jsonObjectsame = JSONObject.parseObject(sameJsonStr);
				JSONArray reviewers = jsonObjectsame.getJSONArray("reviewers");

				for (Object object : reviewers) {
					review = new ReviewJudge();
					review.setInvestigatedId(reviewInvestigated.getId());
					review.setQuestionnaireId(reviewInvestigated.getQuestionnaireId());
					review.setGradeId(Integer.parseInt(jsonObjectsame.getString("id")));
					review.setIssubmission(0);
					review.setFlag(0);
					review.setIsPartake(0);
					review.setCreateBy(accessToken.getUserCode());
					JSONObject jo = (JSONObject) object;
					String name = jo.getString("name");
					String tel = jo.getString("phone");
					if (name != null && !name.equals("") && tel != null && !tel.equals("")) {
						review.setName(name);
						review.setTel(tel);
						reviewjudgemapper.insertSelective(review);

						// 获得评选人姓名as_user，被评选人姓名,url到templateParam
						if (provingMobileUtils.isMobile(tel)) {
							templateParam = new TemplateParamVo();
							StringBuffer str = new StringBuffer(
									"亲爱的" + review.getName() + "，您有一份关于[" + reviewInvestigated.getName()
											+ "]的调查问卷，请点击链接参与评价："+SmsBaseManager.getAppPersonUrl()+"?id="
											+ reviewInvestigated.getId() + "&jd=" + review.getId() + "&qd="
											+ review.getQuestionnaireId() + " 退订回复TD");
							templateParam.setUrl(str.toString());
							templateParam.setPhone(tel);

							templateParamVolist.add(templateParam);
						}
					}

				}
			}

			if (StringUtils.isNotBlank(downJsonStr)) {
				JSONObject jsonObjectdown = JSONObject.parseObject(downJsonStr);
				JSONArray reviewers = jsonObjectdown.getJSONArray("reviewers");

				for (Object object : reviewers) {
					review = new ReviewJudge();
					review.setInvestigatedId(reviewInvestigated.getId());
					review.setQuestionnaireId(reviewInvestigated.getQuestionnaireId());
					review.setGradeId(Integer.parseInt(jsonObjectdown.getString("id")));
					review.setIssubmission(0);
					review.setFlag(0);
					review.setIsPartake(0);
					review.setCreateBy(accessToken.getUserCode());
					JSONObject jo = (JSONObject) object;
					String name = jo.getString("name");
					String tel = jo.getString("phone");
					if (name != null && !name.equals("") && tel != null && !tel.equals("")) {
						review.setName(name);
						review.setTel(tel);
						review.setIsPartake(1);

						reviewjudgemapper.insertSelective(review);

						// 获得评选人姓名as_user，被评选人姓名,url到templateParam
						if (provingMobileUtils.isMobile(tel)) {
							templateParam = new TemplateParamVo();
							StringBuffer str = new StringBuffer(
									"亲爱的" + review.getName() + "，您有一份关于[" + reviewInvestigated.getName()
											+ "]的调查问卷，请点击链接参与评价："+SmsBaseManager.getAppPersonUrl()+"?id="
											+ reviewInvestigated.getId() + "&jd=" + review.getId() + "&qd="
											+ review.getQuestionnaireId() + " 退订回复TD");
							templateParam.setUrl(str.toString());
							templateParam.setPhone(tel);
							templateParamVolist.add(templateParam);
						}
					}

				}
			}

			/**
			 * 发送短信 templateParamVolist：需要发送短信的信息集合 3 ：发送失败后需要重新发送的次数
			 * syncApiClientSmsService：注入
			 */

			if (templateParamVolist.size() != 0) {
				smsSend.getAllDepartments(templateParamVolist, 1);
			}

			return Response.response();
		}

		@Override
		public Result selectInvestigationVoList(ReviewInvestigationVo reviewinvesti,boolean hasRole,int page, int size,
				 String getusercode,AccessToken accessToken) {
//			List<String> userIds= personnelCommenService.findRole(accessToken);
//			if(userIds!=null) {
//				if(userIds.size()==0||userIds.get(0).equals("-1")) {
//					//没有匹配的角色或没有查找到数据
//					return Response.response();
//				}		
//			}
			Map<String, Object> rolesMap = personnelCommenService.findRoleInfoMap(accessToken.getUserCode());    	
			List<String> userquyu= new ArrayList<>();
			
	    	List<DupOrgan> result=null;
	    	
	    	for (Object obj : rolesMap.keySet()) {
	    		String key = (String) obj;
	    		if (key.equals("gj_admin")) {
	    			 userquyu=null;
	    			 rolesMap.put("identitys", null);
	    			 break;
	    		}else if (key.equals("role")) {
	    			 return null;
				}else if (key.equals("gj_Area")) {
					//List<String> liuserquyu=personnelCommenService.findErpRegionByUserCode(accessToken.getUserCode());
					//userquyu=liuserquyu.get(0);
					rolesMap.put("identitys", null);
					
					 result = personnelCommenService.findDupCommByUserCode(accessToken.getUserCode(),null,true);
					for (int i = 0; i < result.size(); i++) {
						userquyu.add(result.get(i).getOrganName());
					}
				}
	    		
	    	}
			
			Page<Object> pageList = PageHelper.startPage(page, size);
			reviewinvesti.setHaseole(hasRole);
			reviewinvesti.setGetusercode(getusercode);
			List<ReviewInvestigationVo> list = personnelAssessmentMapper.selectInvestigationVoList(reviewinvesti,rolesMap,userquyu);
			PageData data = new PageData(pageList);
			data.setData(pageList.getResult());

			return Response.response(data);
		}

		@Override
		public Result resendSms(int investigatedId, String investigatedName, int questionnaireId,
				String questionnaireName) {
			TemplateParamVo templateParam = null;

			List<ReviewJudge> judgeList = personnelAssessmentMapper.selectJudgeTel(investigatedId, questionnaireId);
			List<TemplateParamVo> templateParamVolist = new ArrayList<TemplateParamVo>();
			for (ReviewJudge judge : judgeList) {
				templateParam = new TemplateParamVo();
				StringBuffer str = new StringBuffer("亲爱的" + judge.getName() + "，您有一份关于[" + investigatedName + "-"
						+ questionnaireName + "]的调查问卷，请点击链接参与评价："+SmsBaseManager.getAppPersonUrl()+"?id=" + investigatedId
						+ "&jd=" + judge.getId() + "&qd=" + questionnaireId + " 退订回复TD");
				templateParam.setUrl(str.toString());
				templateParam.setPhone(judge.getTel());
				templateParamVolist.add(templateParam);

			}
			// 发送短信
			if (templateParamVolist.size() != 0) {
				smsSend.getAllDepartments(templateParamVolist, 1);
			}

			return Response.response();
		}

		@Override
		public Result investigationlistedit(ReviewInvestigated reviewInvestigated, AccessToken accessToken) {
			reviewInvestigated.setFlag(1);

			reviewInvestigatedMapper.updateByPrimaryKeySelective(reviewInvestigated);
			return Response.response();
		}

		@Override
		public Result selectAnswerBeforeVo(int investigatedId, int reviewJudgeId, int questionnaireId) {
			ReviewAnswerBeforeVo anserVo = new ReviewAnswerBeforeVo();
			reviewInvestigatedIsRepeatVo investigatedIsRepeatVo = personnelAssessmentMapper
					.selectInvestigatedIsRepeatVo(investigatedId, reviewJudgeId);

			if (investigatedIsRepeatVo.getFlag() == 0) {
				if (investigatedIsRepeatVo.getIsSubmission() == 0) {
					//ReviewQuestionnaireProblemVo
					anserVo = personnelAssessmentMapper.selectAnswerBeforeVo(investigatedId, questionnaireId);
					List<ReviewQuestionnaireProblemVo> queryQuestionnaireProblemVo=personnelAssessmentMapper.queryQuestionnaireProblemVoasse(anserVo.getQuestionnaireId());
					for (ReviewQuestionnaireProblemVo reviewQuestionnaireProblemVo : queryQuestionnaireProblemVo) {
						if(reviewQuestionnaireProblemVo.getType()==3) {
					    	List<ReviewQuestionnaireProblemOptionVo> option=personnelAssessmentMapper.option(reviewQuestionnaireProblemVo.getId());		    	
					    		reviewQuestionnaireProblemVo.setOption(option);			    		
					    }		
					}
					anserVo.setProblemVo(queryQuestionnaireProblemVo);
					
					anserVo.setProblemjianweVo(personnelAssessmentMapper.queryQuestionnaireProblemwendaVoasse(anserVo.getQuestionnaireId()));
				} else if (investigatedIsRepeatVo.getIsSubmission() == 1 && investigatedIsRepeatVo.getIsRepeat() == 1) {
					anserVo = reviewInvestigatedMapper.selectAnswerBeforeVo(investigatedId, questionnaireId);
					List<ReviewQuestionnaireProblemVo> queryQuestionnaireProblemVo=personnelAssessmentMapper.queryQuestionnaireProblemVoasse(anserVo.getQuestionnaireId());
					for (ReviewQuestionnaireProblemVo reviewQuestionnaireProblemVo : queryQuestionnaireProblemVo) {
						if(reviewQuestionnaireProblemVo.getType()==3) {
					    	List<ReviewQuestionnaireProblemOptionVo> option=personnelAssessmentMapper.option(reviewQuestionnaireProblemVo.getId());		    	
					    		reviewQuestionnaireProblemVo.setOption(option);			    		
					    }		
					}
					anserVo.setProblemVo(queryQuestionnaireProblemVo);
					anserVo.setProblemjianweVo(personnelAssessmentMapper.queryQuestionnaireProblemwendaVoasse(anserVo.getQuestionnaireId()));
				}
			}

			anserVo.setInvestigatedIsRepeatVo(investigatedIsRepeatVo);

			return Response.response(anserVo);
		}

		@Override
		public Result updataflag(Integer id, Integer judgeId, Integer questionnaireId) {
			personnelAssessmentMapper.updataflag(id, judgeId, questionnaireId);
			return Response.response();
		}

		@Override
		public Result addScoreAssessment(String answer, String answenwer, AccessToken accessToken) {
			boolean state=false;
			ReviewScore score=null;
	    	JSONArray jsonArray=JSON.parseArray(answer);	    	
	    	JSONArray jsonwenArray=JSON.parseArray(answenwer);
	    		    	
	    	if(jsonArray.size()!=0) {
	    		for(int i=0;i<jsonArray.size();i++) {
	    			score=new ReviewScore();
	    			JSONObject jsonObject=jsonArray.getJSONObject(i);			
	    			score.setJudgeId(jsonObject.getInteger("judgeId"));
	    			score.setProblemId(jsonObject.getInteger("problemId"));
	    			//量表题
	    			if(jsonObject.getInteger("type")==1) {			
	    				score.setScore(jsonObject.getInteger("score"));
	    			
	    			}
	    			
	    			//单选题
	                if(jsonObject.getInteger("type")==3) {
	                	score.setQuestionnaireproblemoptionId(jsonObject.getInteger("potionId"));		
	    				score.setScore(jsonObject.getInteger("score"));				
	    			}
	                score.setFlag(1);
	    			score.setCreateBy(accessToken.getUserCode());		
	    			//提交答案成功后更改评选人的提交状态为已提交
	    				    			
	    			if(reviewScoreMapper.insertSelective(score)>0) {
	    				state=true;				
	    			}else {
	    				logger.error("ReviewScoreService接口异常");
	    				throw new ServiceException("ReviewScoreService接口异常");
	    			}
	    			
	    		}
	    	}
			
			if(jsonwenArray.size()!=0) {
				for(int i=0;i<jsonwenArray.size();i++) {
					score=new ReviewScore();
	    			JSONObject jsonObject=jsonwenArray.getJSONObject(i);			
	    			score.setJudgeId(jsonObject.getInteger("judgeId"));
	    			score.setProblemId(jsonObject.getInteger("problemId"));
	    			//问答题
	    			if(jsonObject.getInteger("type")==2) {			
	    				score.setAnswer(jsonObject.getString("score"));
	    			
	    			}
	    			 score.setFlag(1);
	     			score.setCreateBy(accessToken.getUserCode());		
	     			//提交答案成功后更改评选人的提交状态为已提交
	     			
	     			if(reviewScoreMapper.insertSelective(score)>0) {
	    				state=true;				
	    			}else {
	    				logger.error("ReviewScoreService接口异常");
	    				throw new ServiceException("ReviewScoreService接口异常");
	    			}
				}
				
			}
			
			if(state) {
				ReviewJudge judeg=new ReviewJudge();
				judeg.setId(score.getJudgeId());
				judeg.setIsPartake(1);
				judeg.setIssubmission(1);
				if(reviewjudgemapper.updateByPrimaryKeySelective(judeg)<=0) {
					logger.error("ReviewScoreService接口异常");
					throw new ServiceException("ReviewScoreService接口异常");
				}
			}
			
	    	return Response.response();
		}

		@Override
		public Result perscoreone(int investigatedId) {
			List<PersonnelAssessmentDTO> perslassntscore=personnelAssessmentMapper.perslassntscore(investigatedId);
			return Response.response(perslassntscore);
		}

		@Override
		public Result scoredtos(Integer investigatedid, Integer gradeid,Integer questionnaireId) {
			// TODO Auto-generated method stub
			return Response.response(personnelAssessmentMapper.scoredtos(investigatedid,gradeid,questionnaireId));
		}

		@Override
		public Result scoredtosrj(Integer investigatedid, Integer gradeid,Integer questionnaireId) {
			
			List<ReviewScoreDTO> scoredtosrj=personnelAssessmentMapper.scoredtosrj(investigatedid,gradeid,questionnaireId);
			
			
			
//			List<ReviewScoreDTO> scoredtosrjname=personnelAssessmentMapper.scoredtosrjname(investigatedid,gradeid);
//			
//			
//			List<ReviewScoreperassDTO> reviewscoreperassDTOs=new ArrayList<>();
//			
//			for (int i = 0; i < scoredtosrj.size(); i++) {
//				  for (int j = 0; j < scoredtosrjname.size(); j++) {
//					  
//					  //System.out.println(scoredtosrj.get(j).getRjid()+" "+scoredtosrjname.get(j).getRjid());
//					  if (scoredtosrj.get(j).getRjid().equals(scoredtosrjname.get(j).getRjid())) {
//						 
//						  ReviewScoreperassDTO ReviewScoreperassDTO=new ReviewScoreperassDTO();
//						  ReviewScoreperassDTO.setRjid(scoredtosrjname.get(j).getRjid());
//						  ReviewScoreperassDTO.setRjname(scoredtosrjname.get(j).getRjname());
//						  ReviewScoreperassDTO.setGradename(scoredtosrjname.get(j).getGradename());
//						  reviewscoreperassDTOs.add(ReviewScoreperassDTO);
//					}
//				} 
//			}
//			
	
			
			System.out.println(Response.response(scoredtosrj));

			return Response.response(scoredtosrj);
		}

		@Override
		public Result evaluationproblem(Integer investigatedid,Integer questionnaireId) {
			return Response.response(personnelAssessmentMapper.evaluationproblem(investigatedid,questionnaireId));
		}

		@Override
		public Result evaluateadd(ReviewEvaluate reviewEvaluate, AccessToken accessToken) {
			reviewEvaluate.setFlag(1);
	    	reviewEvaluate.setCreateBy(accessToken.getUserCode()); 
	    	reviewEvaluate.setAdmin(accessToken.getUserCode());
	        reviewEvaluateMapper.insert(reviewEvaluate);
	        return Response.response();
		}

		@Override
		public Result updateedit(ReviewEvaluate rewet, AccessToken accessToken) {
			rewet.setUpdateBy(accessToken.getUserCode());
			rewet.setUpdateTime(new Date());
			personnelAssessmentMapper.updateedit(rewet);
			return Response.response();
		}

		@Override
		public List<ReviewjudgeGradeDTO> reviewjudgegrade(Integer investigatedid, Integer questionnaireId) {
			 return personnelAssessmentMapper.reviewjudgegrade(investigatedid,questionnaireId);
		}

		@Override
		public ReviewRinquDTO reviewrinqu(Integer investigatedid,Integer questionnaireId) {
			return personnelAssessmentMapper.reviewrinqu(investigatedid,questionnaireId);
		}

		@Override
		public List<ReviewScoreProblemDTO> scoreproblemexcl(Integer investigatedid, Integer questionnaireId) {
			return personnelAssessmentMapper.scoreproblemexcl(investigatedid, questionnaireId);
		}

		@Override
		public List<ReviewQuestionnaireProblemDTO> questionoblemsex(Integer questionnaireId,
				Integer investigationmanagementId) {
			return personnelAssessmentMapper.questionoblemsex(questionnaireId,investigationmanagementId);
		}

		@Override
		public List<ReviewQuestionnaireProblemDTO> questionoblemswenex(Integer questionnaireId,
				Integer investigationmanagementId) {
			return personnelAssessmentMapper.questionoblemswenex(questionnaireId,investigationmanagementId);
		}

		@Override
		public List<ReviewScoreProblemDTO> scoreproblemwenexcl(Integer investigatedid, Integer questionnaireId) {
			return personnelAssessmentMapper.scoreproblemwenexcl(investigatedid,questionnaireId);
		}

		@Override
		public Result scoredtost(Integer investigatedid, Integer gradeid,Integer questionnaireId) {
			return Response.response(personnelAssessmentMapper.scoredtos(investigatedid,gradeid,questionnaireId));
		}

		@Override
		public Result scoredtosx(Integer investigatedid, Integer gradeid,Integer questionnaireId) {
			return Response.response(personnelAssessmentMapper.scoredtos(investigatedid,gradeid,questionnaireId));
		}

		@Override
		public Result getlistlishi(Integer investigatedid) {
			return Response.response(personnelAssessmentMapper.getlistlishi(investigatedid));
		}
		
		@Override
		public Result scoreraid(ReviewScoreProblemDTO scoreproblem) {
			
			Integer i=personnelAssessmentMapper.scoreraid(scoreproblem);
			return Response.response(i);
		}
		
		@Override
		public Result reviewevaluate(Integer investigatedid, Integer questionnaireid) {
			
			return Response.response(personnelAssessmentMapper.reviewevaluate(investigatedid, questionnaireid));
		}

		@Override
		public String exxlspersonnelAssessment(PersonnelAssessmentDTO personnelAssessment,Integer is_all,List<String> perseluserid, Map<String, Object> rolesMap, AccessToken accessToken,List<String> userquyu) {
			
//			List<PersonnelAssessmentDTO> dtoper=new ArrayList<PersonnelAssessmentDTO>();
//			List<PersonnelAssessmentDTO> dtoperxin=new ArrayList<PersonnelAssessmentDTO>();
//	      	if (result!=null&&result.size()!=0) {
//	      		for (int i = 0; i < result.size(); i++) {
//	      			List<PersonnelAssessmentDTO> persapper=personnelAssessmentMapper.pernnelAssessment(perseluserid,rolesMap,result.get(i).getOrganName());
//	      			List<PersonnelAssessmentDTO> perxin=personnelAssessmentMapper.exxlspersonneall(rolesMap,result.get(i).getOrganName());
//	      			if (persapper.size()!=0) {
//	      				dtoper.addAll(persapper);
//	  				}  
//	      			if (perxin.size()!=0) {
//	      				dtoperxin.addAll(perxin);
//	  				}    
//	      		}
//	  		}else {
//	  			dtoper =personnelAssessmentMapper.pernnelAssessment(perseluserid,rolesMap,null);
//	  		}
			
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			 String datacrtime=null;
			 String xincrtime=null;
			
			List<ReviewInvestigated> revinveads=personnelAssessmentMapper.revinveaAssessment(perseluserid);
			List<PersonnelAssessmentDTO> scprezong=new ArrayList<PersonnelAssessmentDTO>();
			
	    	List<PersonnelAssessmentDTO> perslassntscore=new ArrayList<PersonnelAssessmentDTO>();
	    	for (int i = 0; i < revinveads.size(); i++) {
	    		perslassntscore.addAll(personnelAssessmentMapper.perslassntscore(revinveads.get(i).getId()));
	    		scprezong.addAll(personnelAssessmentMapper.scprezong(revinveads.get(i).getId()));
			}
	    	//用户   pe.name,pas.id,pe.user_id,rqc.name
	    	//Map<String, Object> rolesMap = personnelCommenService.findRoleInfoMap(accessToken.getUserCode());
	    	List<PersonnelAssessmentDTO> pernnelAsseslidt=new ArrayList<PersonnelAssessmentDTO>();
	    	
	    	if (is_all==1) {//全部
	    		pernnelAsseslidt=personnelAssessmentMapper.pernnelAssessment(personnelAssessment,perseluserid,rolesMap,userquyu);
	    		
			}else if (is_all==0) {//最新
				
				List<PersonnelAssessmentDTO> quan=personnelAssessmentMapper.pernnelAssessment(personnelAssessment,perseluserid,rolesMap,userquyu);
				List<PersonnelAssessmentDTO> exxlspersonneall=personnelAssessmentMapper.exxlspersonneall(rolesMap,userquyu);
				
				for (PersonnelAssessmentDTO persoquan : quan) {
					for (PersonnelAssessmentDTO xin : exxlspersonneall) {
						if (persoquan.getCreatedDate()!=null) {
							datacrtime=formatter.format(persoquan.getCreatedDate());
						}
						
						if (xin.getCreatedDate()!=null) {
							xincrtime=formatter.format(xin.getCreatedDate());
						}
						
						if (persoquan.getUserId().equals(xin.getUserId())&&datacrtime.equals(xincrtime)) {
							pernnelAsseslidt.add(persoquan);
						}
					}
					
				}
				
				
			}
	    	for (int i = 0; i < pernnelAsseslidt.size(); i++) {
        		for (int j = 0; j < scprezong.size(); j++) {
        			if (pernnelAsseslidt.get(i).getId().equals(scprezong.get(j).getId())) {
        				pernnelAsseslidt.get(i).setScore(scprezong.get(j).getScore());
        			}
    			}
    			
    		}
			
	    	//问题分类
	    	List<ReviewQuestionnaireProblemClassification> reviewreProblemClaions=personnelAssessmentMapper.reviewreProblemClaions();
	    	String[] rqpcAry=new String[reviewreProblemClaions.size()];
	    	for (int i = 0; i < reviewreProblemClaions.size(); i++) {
	    		rqpcAry[i]=reviewreProblemClaions.get(i).getName();
			}
	    	
//			构建列表数据
			List<PersonnelAssessmentDTO> personnelAssesDTOS=new ArrayList<PersonnelAssessmentDTO>();
			for (int i = 0; i < pernnelAsseslidt.size(); i++) {
				PersonnelAssessmentDTO peronnelaDTO=new PersonnelAssessmentDTO();
				peronnelaDTO.setId(pernnelAsseslidt.get(i).getId());
				peronnelaDTO.setUserId(pernnelAsseslidt.get(i).getUserId());
				peronnelaDTO.setName(pernnelAsseslidt.get(i).getName());
				peronnelaDTO.setRegionName(pernnelAsseslidt.get(i).getRegionName());
				peronnelaDTO.setEvaluation(pernnelAsseslidt.get(i).getEvaluation());
				peronnelaDTO.setPersonnelId(pernnelAsseslidt.get(i).getPersonnelId());
				peronnelaDTO.setScore(pernnelAsseslidt.get(i).getScore());
				peronnelaDTO.setQuestionnaireId(pernnelAsseslidt.get(i).getQuestionnaireId());
				peronnelaDTO.setInvestigatedId(pernnelAsseslidt.get(i).getInvestigatedId());
				peronnelaDTO.setCreatedBy(pernnelAsseslidt.get(i).getCreatedBy());
				peronnelaDTO.setCreatedName(pernnelAsseslidt.get(i).getCreatedName());
				peronnelaDTO.setCreatedDate(pernnelAsseslidt.get(i).getCreatedDate());
				List<String> list = new ArrayList<>(rqpcAry.length);
				for (int i1 = 0; i1 < rqpcAry.length; i1++) {
					list.add("0");
				}
				peronnelaDTO.setAvgsorce(list);
				personnelAssesDTOS.add(peronnelaDTO);
			}
			
			
//			组装数据
			DecimalFormat df=new DecimalFormat("######0.00");   
			for (PersonnelAssessmentDTO problemas : perslassntscore) {
				int qpcIndex=findAryIndex(problemas.getRqcname(),rqpcAry);
				if (qpcIndex==-1) {
					 continue;
				}
				int detailIndex=findDetailAryIndexas(String.valueOf(problemas.getInvestigatedId()),personnelAssesDTOS);
				if(detailIndex==-1) {
					 continue;
				}			
				PersonnelAssessmentDTO detailDTO = personnelAssesDTOS.get(detailIndex);
				
				if(problemas.getPngjun()!=0.0) {
					detailDTO.getAvgsorce().set(qpcIndex,df.format(problemas.getPngjun()));	
				}else {
					detailDTO.getAvgsorce().set(qpcIndex,"0");	
				}
					
				
			  }
	       
	        JSONObject object=new JSONObject();
			 object.put("data",personnelAssesDTOS);
			
			 object.put("rqc",rqpcAry);
			
	        return object.toString();
		}

		@Override
		public Result delpiliang(String perid) {
			
			List<String> id = JSONArray.parseArray(perid, String.class);
			
			for (int i = 0; i < id.size(); i++) {
				List<PersonnelAssessmentDTO> list=personnelAssessmentMapper.selectdelpas(id.get(i));
				if (list.size()!=0) {
					if (list.get(0).getUserId()!=null) {
						throw new ServiceException("用户编号:"+list.get(0).getUserId()+",下的问卷调查还未结束，不能删除");
					}
					
				}
			}
			
			personnelAssessmentMapper.delupdatepiliang(id);
			
			return Response.response("删除成功");
		}

		@Override
		public Result delpiliangreid(String reid) {
			int de=0;
			List<String> id = JSONArray.parseArray(reid, String.class);
			
			for (int i = 0; i < id.size(); i++) {
				List<ReviewInvestigationVo> selectrerediao=personnelAssessmentMapper.selectrerediao(id.get(i));
				if (selectrerediao.size()==0) {
					classificationVoService.ClassificationFlagUpdateService(Integer.parseInt(id.get(i)));
					ReviewQuestionnaire reviewQuestionnaire = new ReviewQuestionnaire();
					reviewQuestionnaire.setId(Integer.parseInt(id.get(i)));
					reviewQuestionnaire.setFlag(0);
					if (reviewQuestionnaireMapper.updateByPrimaryKeySelective(reviewQuestionnaire) > 0) {
						reviewQuestionnaireProblemMapper.updateProblemFlag(Integer.parseInt(id.get(i)));
						de=1;
						
					}
					
				}else {
					throw new ServiceException("问卷:"+selectrerediao.get(0).getQuestionnaireName()+"未结束，删除失败");
				}
			}
			
		if(de==1) {
			return Response.response("删除成功");
		}
		return Response.response();
		}
	
}