package com.yeejoin.precontrol.common.listener.mqtt;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.typroject.tyboot.component.emq.EmqxListener;
import org.typroject.tyboot.core.foundation.context.RequestContext;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Lists;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.precontrol.common.entity.MessageException;
import com.yeejoin.precontrol.common.entity.Person;
import com.yeejoin.precontrol.common.entity.PersonExamRecord;
import com.yeejoin.precontrol.common.enums.MessageAttributeEnum;
import com.yeejoin.precontrol.common.enums.MessageSubTypeEnum;
import com.yeejoin.precontrol.common.enums.MessageTypeEnum;
import com.yeejoin.precontrol.common.enums.OfflineExamEnum;
import com.yeejoin.precontrol.common.enums.WeChatMsgTemplateTypeEum;
import com.yeejoin.precontrol.common.publish.MessageEventPublish;
import com.yeejoin.precontrol.common.service.ICompanyService;
import com.yeejoin.precontrol.common.service.IMessageExceptionService;
import com.yeejoin.precontrol.common.service.IPersonConditionService;
import com.yeejoin.precontrol.common.service.IPersonExamRecordService;
import com.yeejoin.precontrol.common.service.IPersonExamService;
import com.yeejoin.precontrol.common.service.IPersonService;
import com.yeejoin.precontrol.common.service.ITaskPersonService;
import com.yeejoin.precontrol.common.service.ITaskRiskControlService;
import com.yeejoin.precontrol.common.service.SmallProService;
import com.yeejoin.precontrol.common.utils.DateUtils;
import com.yeejoin.precontrol.common.utils.PlatformUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * @Description: mqtt监听服务
 * @Author: duanwei
 * @Date: 2020/9/15
 */
@Component
@Slf4j
public class ExamMqTtRecordListener extends EmqxListener {

	@Autowired
	ICompanyService iCompanyService;

	@Autowired
	IPersonService iPersonService;

	@Autowired
	IPersonConditionService iPersonConditionService;

	@Autowired
	IMessageExceptionService iMessageExceptionService;

	@Autowired
	IPersonExamService iPersonExamService;

	@Autowired
	ITaskPersonService iTaskPersonService;

	@Autowired
	ITaskRiskControlService iTaskRiskControlService;

	@Autowired
	IPersonExamRecordService iPersonExamRecordService;

	@Autowired
	MessageEventPublish messageEventPublish;

	@Autowired
	SmallProService smallProService;
	
	@Autowired
	PlatformUtils platformUtils;
	
	@Value("${smallProgram.name}")
	String smallPrograName;

	@Override
	public void processMessage(String topic, MqttMessage message) {
		platformUtils.setPlatFormAccess();
		JSONObject jsonObject = null;
		try {
			jsonObject = JSONObject.parseObject(message.toString());
			String examId = jsonObject.getString("examId");
			String userIds = jsonObject.getString("userIds");
			String examinationName = jsonObject.getString("examinationName");
			Long startTime = jsonObject.getLong("startTime");
			Long endTime = jsonObject.getLong("endTime");
			String industryKey = jsonObject.getString("industryKey");
			
			String[] userIdGroup = userIds.split(",");
			if (userIdGroup.length > 0) {
				List<String> userIdList = Arrays.asList(userIdGroup);
				List<PersonExamRecord> recordList = new ArrayList<>();
				userIdList.forEach(i -> {
					PersonExamRecord personExamRecord = new PersonExamRecord();
					personExamRecord.setUserId(Long.valueOf(i));
					personExamRecord.setType(industryKey);
					personExamRecord.setExamName(examinationName);
					personExamRecord.setExamId(Long.valueOf(examId));
					Date start = new Date(startTime);
					personExamRecord.setExamStartTime(start);
					Date end = new Date(endTime);
					personExamRecord.setExamEndTime(end);
					recordList.add(personExamRecord);
				});
				iPersonExamRecordService.saveBatch(recordList);

				// 消息通知--考试创建
				examNotice(userIds, industryKey, examId);
				
				// 微信服务通知
				List<Person> persons = iPersonService.list(new LambdaQueryWrapper<Person>().in(Person::getUserId, Arrays.asList(userIdGroup)).isNotNull(Person::getOpenId));
                List<String> openIds = persons.stream().map(Person::getOpenId).collect(Collectors.toList());
                List<String> messages = new ArrayList<>();
                messages.add(smallPrograName);
                messages.add(examinationName);
                messages.add("xx道提,正确60%以上");
                messages.add(DateUtils.getDateNowString());
				smallProService.sendWeChatUpcomingMessage(openIds, WeChatMsgTemplateTypeEum.TODO.getValue(), messages);
			}
		} catch (Exception e) {
			log.info("考试系统同步消息失败:{}", e.getMessage());
			e.printStackTrace();
			MessageException messageException = new MessageException();
			messageException.setJson(jsonObject.toJSONString());
			messageException.setMessage(e.getMessage());
			iMessageExceptionService.save(messageException);
		}
		log.info("考试系统推送消息同步完成");
	}

	/**
	 * 消息通知--考试创建
	 *
	 * @param userIds 人员列表
	 * @param industryKey 考试类型
	 */
	private void examNotice(String userIds, String industryKey, String examId) {
		FeignClientResult<List<AgencyUserModel>> result = Privilege.agencyUserClient.queryByIds(userIds,true);
		if (result != null) {
			List<AgencyUserModel> userModels = CollectionUtils.isEmpty(result.getResult()) ? new ArrayList<>() :
					result.getResult() ;
			List<Long> personIdList = Lists.transform(userModels, AgencyUserModel::getSequenceNbr);
			MessageTypeEnum typeEnum;
			MessageSubTypeEnum subTypeEnum;
			if (OfflineExamEnum.THREE_SEC.getType().equals(industryKey)) {
				typeEnum = MessageTypeEnum.THREE_LEVEL_EXAM;
				subTypeEnum = MessageSubTypeEnum.THREE_LEVEL_EXAM_TODO;
			} else {
				typeEnum = MessageTypeEnum.SPECIAL_EXAM;
				subTypeEnum = MessageSubTypeEnum.SPECIAL_EXAM_TODO;
			}
			if (!CollectionUtils.isEmpty(personIdList)) {
				personIdList.forEach(personId -> {
					if (personId != null) {
						JSONObject jsonObject = new JSONObject();
						jsonObject.put(MessageAttributeEnum.MSG_TYPE.getName(), typeEnum.getType());
						jsonObject.put(MessageAttributeEnum.MSG_SUB_TYPE.getName(), subTypeEnum.getType());
						jsonObject.put(MessageAttributeEnum.PERSON_ID.getName(), personId);
						jsonObject.put(MessageAttributeEnum.CONTENT.getName(), subTypeEnum.getTip());
						jsonObject.put(MessageAttributeEnum.TASK_ID.getName(), Long.valueOf(examId));
						JSONArray jsonArray = new JSONArray();
						jsonArray.add(jsonObject);
						JSONObject obj = new JSONObject();
						obj.put("param", jsonArray);
						messageEventPublish.publish(obj);
					}
				});
			}
		}
	}
}
