package com.ym.mec.biz.service.impl;

import com.ym.mec.biz.dal.dao.*;
import com.ym.mec.biz.dal.dto.QuestionnaireUserResultDto;
import com.ym.mec.biz.dal.entity.ClassGroupStudentMapper;
import com.ym.mec.biz.dal.entity.QuestionnaireQuestion;
import com.ym.mec.biz.dal.entity.QuestionnaireQuestionItem;
import com.ym.mec.biz.dal.page.ReplacementInstrumentActivityQueryInfo;
import com.ym.mec.common.dal.BaseDAO;
import com.ym.mec.common.exception.BizException;
import com.ym.mec.common.page.PageInfo;
import com.ym.mec.common.page.QueryInfo;
import com.ym.mec.util.collection.MapUtil;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import com.ym.mec.common.service.impl.BaseServiceImpl;
import com.ym.mec.biz.dal.entity.QuestionnaireUserResult;
import com.ym.mec.biz.service.QuestionnaireUserResultService;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class QuestionnaireUserResultServiceImpl extends BaseServiceImpl<Long, QuestionnaireUserResult>  implements QuestionnaireUserResultService {
	
	@Autowired
	private QuestionnaireUserResultDao questionnaireUserResultDao;
	@Autowired
	private QuestionnaireQuestionItemDao questionnaireQuestionItemDao;
	@Autowired
	private QuestionnaireQuestionDao questionnaireQuestionDao;
	@Autowired
	private TeacherDao teacherDao;

	@Override
	public BaseDAO<Long, QuestionnaireUserResult> getDAO() {
		return questionnaireUserResultDao;
	}

	@Override
	public void batchInsert(List<QuestionnaireUserResult> questionnaireUserResultList) {
		questionnaireUserResultDao.batchInsert1(questionnaireUserResultList);
	}

	@Override
	public Object queryDetailPage(QueryInfo queryInfo) {
		PageInfo<QuestionnaireUserResultDto> pageInfo = new PageInfo<>(queryInfo.getPage(), queryInfo.getRows());
		Map<String, Object> params = new HashMap<String, Object>();
		MapUtil.populateMap(params, queryInfo);

		List<QuestionnaireUserResultDto> dataList = null;
		int count = questionnaireUserResultDao.findDetailCount(params);
		if (count > 0) {
			pageInfo.setTotal(count);
			params.put("offset", pageInfo.getOffset());
			dataList = questionnaireUserResultDao.queryDetailPage(params);
		}
		if (count == 0) {
			dataList = new ArrayList<>();
		}
		pageInfo.setRows(dataList);
		return pageInfo;
	}

	@Override
	public Map<String,Object> questionnaireUserResultExport(Integer cooperationId,List<QuestionnaireQuestion> questionList) {
		HashMap<String, Object> paramMap = new HashMap<>(2);
		paramMap.put("activeId",cooperationId);
		List<QuestionnaireUserResult> userResults = questionnaireUserResultDao.findAll(paramMap);

		Map<String,Object> resultMap = new HashMap<>(2);
		//导出列表数据
		List<Map<String,Object>> jsonObjectList = new ArrayList<>();
		Set<String> body = new LinkedHashSet<>();

		if(userResults != null && userResults.size() > 0){
			//获取所有的问题列表
			List<Long> questionIdList = questionList.stream().map(e -> e.getId()).collect(Collectors.toList());
			Map<Long, List<QuestionnaireQuestion>> questionMap = questionList.stream().collect(Collectors.groupingBy(QuestionnaireQuestion::getId));
			//获取所有答案列表
			paramMap.put("questionIdList",questionIdList);
			List<QuestionnaireQuestionItem> questionItemList = questionnaireQuestionItemDao.findAll(paramMap);
			Map<Long, List<QuestionnaireQuestionItem>> questionItemMap = questionItemList.stream().collect(Collectors.groupingBy(QuestionnaireQuestionItem::getId));
			//按学员分组
			Map<Integer, List<QuestionnaireUserResult>> userIdMap = userResults.stream().collect(Collectors.groupingBy(QuestionnaireUserResult::getUserId));
			List<Integer> userIdList = new ArrayList<>(userIdMap.keySet());
			Collections.sort(userIdList);
			Map<Integer, String> nameList = MapUtil.convertMybatisMap(questionnaireQuestionItemDao.queryUserName(cooperationId));
			Map<Integer, String> phoneList = MapUtil.convertMybatisMap(teacherDao.queryPhoneByIds(StringUtils.join(userIdList,",")));
			for (Integer userId : userIdList) {
				List<QuestionnaireUserResult> userResultList = userIdMap.get(userId);
				if(userResultList != null && userResultList.size() > 0){
					Map<String,Object> jsonObject = new LinkedHashMap<>();
					body.add("cooperationId");
					body.add("userId");
					body.add("userName");
					body.add("phone");
					jsonObject.put("cooperationId",cooperationId);
					jsonObject.put("userId",userId);
					jsonObject.put("userName",nameList.get(userId));
					jsonObject.put("phone",phoneList.get(userId));
					//分解当前学员答案
					for (QuestionnaireUserResult result : userResultList) {
						//获取问题列表
						QuestionnaireQuestion question = questionMap.get(result.getQuestionnaireQuestionId()).get(0);
						String questionnaireQuestionItemIdList = result.getQuestionnaireQuestionItemIdList();
						StringBuffer userResult = new StringBuffer();
						if(StringUtils.isNotEmpty(questionnaireQuestionItemIdList)){
							String[] split = questionnaireQuestionItemIdList.split(",");
							for (String s : split) {
								List<QuestionnaireQuestionItem> items = questionItemMap.get(Long.parseLong(s));
								userResult.append(items.get(0).getAnswerValue()).append("\n");
							}
						}
						String additionalValue = result.getAdditionalValue();
						if(StringUtils.isNotEmpty(additionalValue)){
							userResult.append(additionalValue);
						}
						body.add(question.getContent());
						jsonObject.put(question.getContent(),userResult.toString());
					}
					jsonObjectList.add(jsonObject);
				}
			}
		}
		resultMap.put("jsonObjectList",jsonObjectList);
		resultMap.put("body",body);
		return resultMap;
	}
}