package cn.com.countrygarden.bi.main.service.review.impl;

import cn.com.countrygarden.bi.main.core.Response;
import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.dao.review.ReviewJudgeMapper;
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.ReviewScoreMapper;
import cn.com.countrygarden.bi.main.dto.ProblemDetailDTO;
import cn.com.countrygarden.bi.main.dto.ReviewQuestionnaireProblemDTO;
import cn.com.countrygarden.bi.main.dto.ReviewScoreProblemDTO;
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.model.AccessToken;
import cn.com.countrygarden.bi.main.model.PageData;
import cn.com.countrygarden.bi.main.model.review.ReviewEvaluate;
import cn.com.countrygarden.bi.main.model.review.ReviewJudge;
import cn.com.countrygarden.bi.main.model.review.ReviewQuestionnaireProblem;
import cn.com.countrygarden.bi.main.model.review.ReviewScore;
import cn.com.countrygarden.bi.main.service.review.ReviewScoreService;
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 org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example.Criteria;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 评选结果-业务逻辑层实现
 *
 * @author 汤婷
 * @email www.justintoforest@gamail.com
 * @url 
 * @date 2018-06-25
 */
@Service
@Transactional
public class ReviewScoreServiceImpl implements ReviewScoreService {
    @Autowired
    private ReviewScoreMapper reviewScoreMapper;
    
    @Autowired
    private ReviewQuestionnaireProblemOptionMapper reviewquestionnaireProblemOptionMapper;
    @Autowired
    private ReviewJudgeMapper judgeMapper;
    
    private final Logger logger = LoggerFactory.getLogger(getClass());
    @Override
    public Result queryPageList(ReviewScore reviewScore, int page, int size) {
        Page<Object> pageList = PageHelper.startPage(page, size);
        Condition condition=new Condition(ReviewScore.class);
        Criteria criteria = condition.createCriteria();
//		TODO 添加条件
		reviewScoreMapper.selectByCondition(condition);
        PageData data=new PageData(pageList);
        data.setData(pageList.getResult());
        return Response.response(data);
    }

    
    public Result queryById(Integer id) {
        return Response.response(reviewScoreMapper.selectByPrimaryKey(id));
    }


   
	@Override
    public Result add(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(judgeMapper.updateByPrimaryKeySelective(judeg)<=0) {
				logger.error("ReviewScoreService接口异常");
				throw new ServiceException("ReviewScoreService接口异常");
			}
		}
		
    	return Response.response();
		
	}
    public Result edit(ReviewScore reviewScore, AccessToken accessToken) {
    	reviewScoreMapper.updateByPrimaryKey(reviewScore);
    	return Response.response();
        
    }

    @Override
    public Result del(Integer id) {
        int count = reviewScoreMapper.deleteByPrimaryKey(id);
        return Response.response(count);
    }
    
	@Override
	public Result scoredtos(Integer investigatedid,Integer gradeid) {
		// TODO Auto-generated method stub
		return Response.response(reviewScoreMapper.scoredtos(investigatedid,gradeid));
	}
	
	@Override
	public Result scoredtosx(Integer investigatedid,Integer gradeid) {
		// TODO Auto-generated method stub
		return Response.response(reviewScoreMapper.scoredtos(investigatedid,gradeid));
	}
	
	@Override
	public Result scoredtost(Integer investigatedid,Integer gradeid) {
		// TODO Auto-generated method stub
		return Response.response(reviewScoreMapper.scoredtos(investigatedid,gradeid));
	}

	@Autowired
	private ReviewQuestionnaireProblemMapper reviewQuestionnaireProblemMapper;
	@Autowired
	private ReviewJudgeMapper reviewJudgeMapper;
	@Override
	public Result scoreproblem(ReviewScoreProblemDTO scoreproblem, int page, int size) {
		Page<Object> pageList = new Page<>();
		List<ReviewScoreProblemDTO> reviewScorDTO=reviewScoreMapper.scoreproblem(scoreproblem);
		PageData data = new PageData(pageList);

		Condition condition=new Condition(ReviewQuestionnaireProblem.class);
		condition.createCriteria()
				.andEqualTo("questionnaireId",scoreproblem.getQuestionnaireId());
		//List<ReviewQuestionnaireProblem> questionnaireProblems = reviewQuestionnaireProblemMapper.selectByCondition(condition);

		List<ReviewQuestionnaireProblemDTO> questionnaireProblems = reviewQuestionnaireProblemMapper.questionnaireProblems(Integer.parseInt(scoreproblem.getQuestionnaireId()),scoreproblem.getInvestigationmanagementId());

		Condition condition1=new Condition(ReviewJudge.class);
		condition1.createCriteria()
				.andEqualTo("investigatedId",scoreproblem.getInvestigatedid())
				.andEqualTo("questionnaireId",scoreproblem.getQuestionnaireId())
				.andEqualTo("gradeId",scoreproblem.getRgname());
		List<ReviewJudge> judges = reviewJudgeMapper.selectByCondition(condition1);
//		人员信息
		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 evaluationproblem(Integer investigatedid) {
	
		return Response.response(reviewScoreMapper.evaluationproblem(investigatedid));
	}


	@Override
	public List<ReviewScoreProblemDTO> evaluationproblemexport(Integer investigatedid) {
		
		return reviewScoreMapper.evaluationproblem(investigatedid);
	}

	@Override
	public Result updateedit(ReviewEvaluate rewet, AccessToken accessToken) {
		
//		JSONArray reviewers = JSONArray.parseArray(reviewScore);
//		
//		for (int i = 0; i < reviewers.size(); i++) {
//			ReviewScore rscore=new ReviewScore();
//			JSONObject obj = reviewers.getJSONObject(i);
//			Integer id=obj.getInteger("id");
//			String answer=obj.getString("answer");
//		
//			Integer score=obj.getInteger("score");
//			rscore.setId(id);
//			rscore.setAnswer(answer);
//			rscore.setScore(score);
//			reviewScoreMapper.updateedit(rscore);
//		}
		
		rewet.setUpdateBy(accessToken.getUserCode());
		rewet.setUpdateTime(new Date());
		reviewScoreMapper.updateedit(rewet);
		return Response.response();
	}

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


	@Override
	public Result delsoce(Integer judgeId) {
		reviewScoreMapper.delsoce(judgeId);
		return Response.response();
	}


	@Override
	public Result scoreraid(ReviewScoreProblemDTO scoreproblem) {
		//reviewScoreMapper.scoreraid(scoreproblem);
		Integer i=reviewScoreMapper.scoreraid(scoreproblem);
		return Response.response(i);
	}


	@Override
	public Result reviewevaluate(Integer investigatedid, Integer questionnaireid) {
		
		return Response.response(reviewScoreMapper.reviewevaluate(investigatedid, questionnaireid));
	}


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


	@Override
	public ReviewRinquDTO reviewrinqu(Integer investigatedid) {
		
		return reviewScoreMapper.reviewrinqu(investigatedid);
	}


	@Override
	public List<ReviewScoreProblemDTO> scoreproblemexcl(Integer investigatedid, Integer questionnaireId) {
		// TODO Auto-generated method stub
		return reviewScoreMapper.scoreproblemexcl(investigatedid, questionnaireId);
	}


	@Override
	public List<ReviewScoreProblemDTO> scoreproblemwenexcl(Integer investigatedid, Integer questionnaireId) {
		// TODO Auto-generated method stub
		return reviewScoreMapper.scoreproblemwenexcl(investigatedid,questionnaireId);
	}


	



}