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

import com.ym.mec.auth.api.client.SysUserFeignService;
import com.ym.mec.auth.api.entity.SysUser;
import com.ym.mec.biz.dal.dao.*;
import com.ym.mec.biz.dal.dto.QuestionnaireUserResultDto;
import com.ym.mec.biz.dal.dto.ReplacementInstrumentActivityDto;
import com.ym.mec.biz.dal.entity.QuestionnaireQuestion;
import com.ym.mec.biz.dal.entity.QuestionnaireQuestionItem;
import com.ym.mec.biz.dal.entity.QuestionnaireTopic;
import com.ym.mec.biz.dal.entity.QuestionnaireUserResult;
import com.ym.mec.biz.dal.enums.QuestionnaireActiveTypeEnum;
import com.ym.mec.biz.dal.page.QuestionnaireUserResultQueryInfo;
import com.ym.mec.biz.service.QuestionnaireUserResultService;
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.common.service.impl.BaseServiceImpl;
import com.ym.mec.util.collection.MapUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Instant;
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 QuestionnaireTopicDao questionnaireTopicDao;
	@Autowired
	private SysUserFeignService sysUserFeignService;
	@Autowired
	private TeacherDao teacherDao;
	@Autowired
	private StudentDao studentDao;

	@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> getExportBody(QuestionnaireTopic topic,List<QuestionnaireQuestion> questionList) {
		HashMap<String, Object> paramMap = new HashMap<>(2);
		paramMap.put("topicId",topic.getId());
		paramMap.put("tenantId",topic.getTenantId());
		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));
			//按学员分组
			Set<Integer> userIdSet = new LinkedHashSet<>();
			for (QuestionnaireUserResult userResult : userResults) {
				userIdSet.add(userResult.getUserId());
			}
			List<Integer> userIdList = new ArrayList<>(userIdSet);
			Map<Integer, String> nameList = null;
			Map<Integer, List<QuestionnaireUserResult>> userIdMap = userResults.parallelStream().collect(Collectors.groupingBy(QuestionnaireUserResult::getUserId));
			Map<Integer, String> phoneList = null;
			Map<Integer, String> organNameMap = null;
			Boolean isLogin = topic.getLoginFlag() == 1;
			if(isLogin){
				nameList = MapUtil.convertMybatisMap(questionnaireUserResultDao.queryUserName(topic.getId()));
				phoneList = MapUtil.convertMybatisMap(teacherDao.queryPhoneByIds(StringUtils.join(userIdList,",")));
				organNameMap = MapUtil.convertMybatisMap(studentDao.queryStudentOrganNameMap(userIdList));
			}
			for (Integer userId : userIdList) {
				List<QuestionnaireUserResult> userResultList = userIdMap.get(userId);
				if(userResultList != null && userResultList.size() > 0){
					QuestionnaireUserResult result1 = userResultList.get(0);
					Map<String,Object> jsonObject = new LinkedHashMap<>();
					if(isLogin){
						body.add("organName");
						jsonObject.put("organName",organNameMap.get(userId));
						body.add("userId");
						jsonObject.put("userId",userId);
						body.add("userName");
						jsonObject.put("userName",nameList.get(userId));
						body.add("phone");
						jsonObject.put("phone",phoneList.get(userId));
					}
					body.add("createTime");
					jsonObject.put("createTime",result1.getCreateTime());
					//分解当前学员答案
					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;
	}

    @Override
	@Transactional(rollbackFor = Exception.class)
    public void add(ReplacementInstrumentActivityDto replacementInstrumentActivity) {
		Integer topicId = replacementInstrumentActivity.getTopicId();
		QuestionnaireTopic topic = questionnaireTopicDao.get(topicId);
		if(topic.getStatus() == 0){
			throw new BizException("当前问卷已停用");
		}
		if(topic.getLoginFlag() == 1){
			SysUser sysUser = sysUserFeignService.queryUserInfo();
			if (sysUser == null) {
				throw new BizException("用户信息获取失败，请重新登陆");
			}
			if (!sysUser.getTenantId().equals(topic.getTenantId())) {
				throw new BizException("您不可填写该问卷: 请联系教务老师");
			}
			List<QuestionnaireUserResult> questionnaireUserResultList = replacementInstrumentActivity.getQuestionnaireUserResultList();
			if(questionnaireUserResultList == null || questionnaireUserResultList.size() == 0){
				throw new BizException("请填写问卷结果");
			}
			QuestionnaireActiveTypeEnum activeType = replacementInstrumentActivity.getActiveType();
			HashMap<String, Object> paramMap = new HashMap<>(4);
			paramMap.put("activeId",replacementInstrumentActivity.getReplacementInstrumentCooperationId());
			paramMap.put("activeType",activeType);
			paramMap.put("userId",sysUser.getId());
			paramMap.put("topicId",topicId);
//			List<QuestionnaireUserResult> userResults = questionnaireUserResultDao.findAll(paramMap);
//			if(userResults != null && userResults.size() > 0){
//				throw new BizException("您已提交问卷，请勿重复操作");
//			}
			//删除原来的问卷结果
			questionnaireUserResultDao.delByActiveIdAndUserId(paramMap);
			for (QuestionnaireUserResult result : questionnaireUserResultList) {
				result.setUserId(sysUser.getId());
				result.setQuestionnaireTopicId(topicId);
				result.setActiveType(activeType);
			}
			//新增问卷结果
			questionnaireUserResultDao.batchInsert1(questionnaireUserResultList);
		}else {
			this.addResult(replacementInstrumentActivity);
		}
	}

    @Override
	@Transactional(rollbackFor = Exception.class)
    public void addResult(ReplacementInstrumentActivityDto replacementInstrumentActivity) {
		Integer topicId = replacementInstrumentActivity.getTopicId();

		List<QuestionnaireUserResult> questionnaireUserResultList = replacementInstrumentActivity.getQuestionnaireUserResultList();
		if(questionnaireUserResultList == null || questionnaireUserResultList.size() == 0){
			throw new BizException("请填写问卷结果");
		}
		int epochSecond = (int)Instant.now().getEpochSecond();
		for (QuestionnaireUserResult result : questionnaireUserResultList) {
			result.setUserId(epochSecond);
			result.setQuestionnaireTopicId(topicId);
			result.setActiveType(QuestionnaireActiveTypeEnum.ENTERPRISE_CUSTOMIZATION);
		}
		//新增问卷结果
		questionnaireUserResultDao.batchInsert1(questionnaireUserResultList);
    }

	@Override
	public PageInfo<QuestionnaireUserResultDto> queryResultPage(QuestionnaireUserResultQueryInfo 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.countResultCount(params);
		if (count > 0) {
			pageInfo.setTotal(count);
			params.put("offset", pageInfo.getOffset());
			dataList = questionnaireUserResultDao.findResultCount(params);
		}
		if (count == 0) {
			dataList = new ArrayList<>();
		}
		pageInfo.setRows(dataList);
		return pageInfo;
	}

	@Override
	public QuestionnaireUserResultDto queryUserResult(Integer topicId) {
		SysUser sysUser = sysUserFeignService.queryUserInfo();
		return questionnaireUserResultDao.queryUserResult(topicId,sysUser.getId());
	}

	@Override
	public String[] getExportHeader(QuestionnaireTopic topic,List<QuestionnaireQuestion> questionList) {
		if(questionList != null && questionList.size() > 0) {
			List<String> column = new ArrayList<>();
			if (topic.getLoginFlag() == 1) {
				column.add("分部");
				column.add("学员编号");
				column.add("学员姓名");
				column.add("手机号");
			}
			column.add("提交时间");

			List<String> collect = questionList.stream().map(e -> e.getContent()).collect(Collectors.toList());
			column.addAll(collect);
			return column.toArray(new String[column.size()]);
		}
		return new String[0];
	}
}