package cn.com.countrygarden.bi.main.service.canteen.impl;
import cn.com.countrygarden.bi.main.core.Response;
import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.dao.canteen.CanteenScoreMapper;
import cn.com.countrygarden.bi.main.dao.dup.TbHsprContractMapper;
import cn.com.countrygarden.bi.main.dto.CanteenScoresocedaanDTO;
import cn.com.countrygarden.bi.main.dto.CanteenScorestatisticsDTO;
import cn.com.countrygarden.bi.main.dto.canteenProblemDetaiDTO;
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.canteen.CanteenScore;
import cn.com.countrygarden.bi.main.model.review.ReviewQuestionnaireProblem;
import cn.com.countrygarden.bi.main.service.canteen.CanteenScoreService;
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 tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example.Criteria;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 饭堂调查得分-业务逻辑层实现
 *
 * @author 吕伟峰
 * @email www.justintoforest@gamail.com
 * @url 
 * @date 2018-08-13
 */
@Service
public class CanteenScoreServiceImpl implements CanteenScoreService{
    @Autowired
    private CanteenScoreMapper canteenScoreMapper;
    
    @Autowired
    private TbHsprContractMapper tbhsprcontractmapper;

    private final Logger logger = LoggerFactory.getLogger(getClass());
    @Override
    public Result queryPageList(CanteenScore canteenScore, int page, int size) {
        Page<Object> pageList = PageHelper.startPage(page, size);
        Condition condition=new Condition(CanteenScore.class);
        Criteria criteria = condition.createCriteria();
//		TODO 添加条件
		canteenScoreMapper.selectByCondition(condition);
        PageData data=new PageData(pageList);
        data.setData(pageList.getResult());
        return Response.response(data);
    }

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

    @Override
    public Result add(String answer, AccessToken accessToken) {
    	
    	boolean state=false;
    	CanteenScore canteesore=null;
    	
    	
       JSONArray jsonArray=JSON.parseArray(answer);	
       //JSONArray jsonwenArray=JSON.parseArray(answenwer);	
       
       if(jsonArray.size()!=0) {
           for(int i=0;i<jsonArray.size();i++) {
        	   canteesore=new CanteenScore();
        	   JSONObject jsonObject=jsonArray.getJSONObject(i);
        	   canteesore.setStaffId(jsonObject.getString("bdid"));
        	   canteesore.setName(jsonObject.getString("name"));
        	   canteesore.setInvestigateId(jsonObject.getInteger("canteeninsdid"));
        	   canteesore.setProblemId(jsonObject.getInteger("problemId"));
        	   canteesore.setDepname(jsonObject.getString("depname"));
        	 //量表题
    			if(jsonObject.getInteger("type")==1) {			
    				canteesore.setScore(jsonObject.getInteger("score"));
    			
    			}

    			//单选题
               if(jsonObject.getInteger("type")==3) {
            	   canteesore.setQuestionnaireproblemoptionId(jsonObject.getInteger("potionId"));		
            	   canteesore.setScore(jsonObject.getInteger("score"));				
    			}
               
               if(jsonObject.getInteger("type")==4) {//简答题
         	 	
         	      canteesore.setAnswer(jsonObject.getString("anwen"));				
 			   }
               
             //问答题
    			if(jsonObject.getInteger("type")==2) {			
    				canteesore.setAnswer(jsonObject.getString("anwen"));
    			
    			}

               canteesore.setFlag(1);
               canteesore.setCreateBy(accessToken.getUserCode());		
    			//提交答案成功后更改评选人的提交状态为已提交
    			
    			
    			if(canteenScoreMapper.insertSelective(canteesore)>0) {
    				state=true;				
    			}else {
    				logger.error("ReviewScoreService接口异常");
    				throw new ServiceException("ReviewScoreService接口异常");
    			}
        	   
           }
       }
       
//       if(jsonwenArray.size()!=0) {
//    	   for(int i=0;i<jsonwenArray.size();i++) {
//        	   canteesore=new CanteenScore();
//        	   JSONObject jsonObject=jsonwenArray.getJSONObject(i);
//        	   canteesore.setStaffId(jsonObject.getString("bdid"));
//        	   canteesore.setName(jsonObject.getString("name"));
//        	   canteesore.setInvestigateId(jsonObject.getInteger("canteeninsdid"));
//        	   canteesore.setProblemId(jsonObject.getInteger("problemId"));
//        	   canteesore.setDepname(jsonObject.getString("depname"));
//             if(jsonObject.getInteger("type")==4) {//简答题
//          	 	
//          	   canteesore.setAnswer(jsonObject.getString("score"));				
//  			}
//             
// 			//问答题
// 			if(jsonObject.getInteger("type")==2) {			
// 				canteesore.setAnswer(jsonObject.getString("score"));
// 			
// 			}
// 			
// 			 canteesore.setFlag(1);
//             canteesore.setCreateBy(accessToken.getUserCode());		
//  			//提交答案成功后更改评选人的提交状态为已提交
//  			
//  			
//  			if(canteenScoreMapper.insertSelective(canteesore)>0) {
//  				state=true;				
//  			}else {
//  				logger.error("ReviewScoreService接口异常");
//  				throw new ServiceException("ReviewScoreService接口异常");
//  			}
//        	   
//    	   }
//       }

    	
        return Response.response();
    }

    @Override
    public Result edit(CanteenScore canteenScore, AccessToken accessToken) {
        canteenScoreMapper.updateByPrimaryKey(canteenScore);
        return Response.response();
    }

    @Override
    public Result del(Integer id) {
        int count = canteenScoreMapper.deleteByPrimaryKey(id);
        return Response.response(count);
    }
    
    @Override
	public Result bdpsndoccadati(String bdid, int canteeninsdid) {
		List<CanteenScore> bdpcadati=canteenScoreMapper.bdpsndoccadati(bdid, canteeninsdid);
		return Response.response(bdpcadati);
	}

	@Override
	public Result updatescore(String bdid, int canteeninsdid) {
		canteenScoreMapper.updatescore(bdid, canteeninsdid);
		canteenScoreMapper.deletescore();
		return Response.response();
	}

	@Override
	public Result getcascore(CanteenScorestatisticsDTO cantesore, int page, int size) {
	
		
		 Page<Object> pageList = PageHelper.startPage(page, size);
		 List<CanteenScorestatisticsDTO> canteensorcedto=canteenScoreMapper.getcascore(cantesore);
		
		 PageData data=new PageData(pageList);
	      data.setData(pageList.getResult());
	      return Response.response(data);
	}

	@Override
	public Result viewdetailsv(Integer rqid, Integer ciid) {
		
		Page<Object> pageList = new Page<>();
		 List<CanteenScoresocedaanDTO> candaan=canteenScoreMapper.socedaan(rqid,ciid);
		 PageData data = new PageData(pageList);
		 
		 List<ReviewQuestionnaireProblem> canscwenti=canteenScoreMapper.soceranwen(ciid,rqid);


//			问题信息
			String[] canscwentiAry=new String[canscwenti.size()];
			for (int i = 0; i < canscwenti.size(); i++) {
				canscwentiAry[i]=canscwenti.get(i).getTitleDescription();
			}
			
//			问题信息id
			String[] canscwentiAryid=new String[canscwenti.size()];
			for (int i = 0; i < canscwenti.size(); i++) {
				canscwentiAryid[i]=canscwenti.get(i).getTitleid();
			}
						
		
//			构建列表数据 
			List<canteenProblemDetaiDTO> caproblemDTOS =new ArrayList<canteenProblemDetaiDTO>();
			//caproblemDTOS.clear();
			for (int i = 0; i < candaan.size();i++) {
				canteenProblemDetaiDTO canprdt=new canteenProblemDetaiDTO();
				canprdt.setId(candaan.get(i).getId());
				canprdt.setStaffId(candaan.get(i).getStaffId());
				canprdt.setName(candaan.get(i).getName());
				canprdt.setCreateTime(candaan.get(i).getCreateTime());
				canprdt.setQuestionnaireproblemoptionId(candaan.get(i).getQuestionnaireproblemoptionId());
				canprdt.setDepname(candaan.get(i).getDepname());
				canprdt.setTypeid(candaan.get(i).getTypeid());
				canprdt.setProblemId(candaan.get(i).getProblemId());
				canprdt.setRqponame(candaan.get(i).getRqponame());
				canprdt.setQuestionnaireproblemoptionId(candaan.get(i).getQuestionnaireproblemoptionId());
				List<String> list = new ArrayList<>(canscwentiAry.length);
				for (int i1 = 0; i1 < canscwentiAry.length; i1++) {
					list.add("");
				}
				canprdt.setScoreanswer(list);
				caproblemDTOS.add(canprdt);
			}
		 
//			组装数据
			for(CanteenScoresocedaanDTO canstdo : candaan) {
				
				int proIndex=findAryIndex(canstdo.getProblemId(),canscwentiAryid);
				int detailIndex=findDetailAryIndex(canstdo.getStaffId(),caproblemDTOS);
				canteenProblemDetaiDTO canteenpr=caproblemDTOS.get(detailIndex);
				if(canstdo.getRqponame()!=null) {
					System.out.println(proIndex+"  "+canstdo.getRqponame());
					canteenpr.getScoreanswer().set(proIndex, canstdo.getRqponame());
					
				}
				if(canstdo.getScore()!=null) {
					if(canstdo.getTypeid()==3) {
						System.out.println(proIndex+"  "+canstdo.getRqponame()+" "+canstdo.getScore());
						canteenpr.getScoreanswer().set(proIndex, canstdo.getRqponame()+"("+canstdo.getScore()+"分"+")");
					}else {
						System.out.println(proIndex+"  "+canstdo.getScore());
						canteenpr.getScoreanswer().set(proIndex, canstdo.getScore()+"分");
					}
					
				}
				if(StringUtils.isNotBlank(canstdo.getAnswer())) {
					System.out.println(proIndex+"  "+canstdo.getAnswer());
					canteenpr.getScoreanswer().set(proIndex, canstdo.getAnswer());
					
				}
			}
			
               for (int i = 0; i < caproblemDTOS.size(); i++) {
				
				for (int j = 0; j < caproblemDTOS.get(i).getScoreanswer().size(); j++) {
					 
					if(StringUtils.isNotBlank(caproblemDTOS.get(i).getScoreanswer().get(j))) {
						            System.out.println(caproblemDTOS.get(i).getScoreanswer().get(j));
					}
				}
				
			}
															
			Set<canteenProblemDetaiDTO> set=new HashSet<canteenProblemDetaiDTO>();
			for (int i = 0; i < caproblemDTOS.size(); i++) {
				
				for (int j = 0; j < caproblemDTOS.get(i).getScoreanswer().size(); j++) {
					 
					if(StringUtils.isNotBlank(caproblemDTOS.get(i).getScoreanswer().get(j))) {
						set.add(caproblemDTOS.get(i));
					}
				}
				
			}
			data.setData(set);
			
		 JSONObject object=new JSONObject();
		 object.put("data",data);
		
		 object.put("canscwenti",canscwentiAry);
		 System.out.println(object);
		 return Response.response(object);
	}
	
	private int findDetailAryIndex(String id, List<canteenProblemDetaiDTO> canteenpr) {
		for (int i = 0; i < canteenpr.size(); i++) {
			if(canteenpr.get(i).getStaffId().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 canteenareatu(String areaId) {
		List<CanteenScorestatisticsDTO> canteenareatu=canteenScoreMapper.canteenareatu(areaId);
		
		return Response.response(canteenareatu);
	}

	@Override
	public Result canteenprojectu(String areaId) {
		List<CanteenScorestatisticsDTO> canteenprojectu=canteenScoreMapper.canteenprojectu(areaId);

		return Response.response(canteenprojectu);
	}

}