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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.yeejoin.precontrol.common.entity.PersonMessage;
import com.yeejoin.precontrol.common.enums.MessageAttributeEnum;
import com.yeejoin.precontrol.common.listener.event.MessageEvent;
import com.yeejoin.precontrol.common.service.IPersonMessageService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

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

/**
 * @description: 消息服务监听器
 * @author: tb
 * @date: 2021-02-23 17:20
 **/
@Component
@Slf4j
public class MessageEventListener implements ApplicationListener<MessageEvent> {

	@Autowired
	IPersonMessageService personMessageService;

	@Async
	@SneakyThrows
	@Override
	public void onApplicationEvent(MessageEvent messageEvent) {
		JSONObject jsonObject = messageEvent.getMsg2();
		log.info("接收到消息数据,data:{}", jsonObject.toJSONString());
		JSONArray jsonArray = jsonObject.getJSONArray("param");
		savePersonMessage(jsonArray);
	}

	private void savePersonMessage(JSONArray jsonArray) {
		List<PersonMessage> allPersonMessage = Lists.newArrayList();
		jsonArray.forEach(o -> {
			JSONObject jsonObject = (JSONObject) o;
			PersonMessage personMessage = new PersonMessage();
			personMessage.setCreateDate(new Date());
			personMessage.setSubType(jsonObject.getLong(MessageAttributeEnum.MSG_SUB_TYPE.getName()));
			personMessage.setPersonId(jsonObject.getLong(MessageAttributeEnum.PERSON_ID.getName()));
			personMessage.setType(jsonObject.getInteger(MessageAttributeEnum.MSG_TYPE.getName()));
			personMessage.setContent(jsonObject.getString(MessageAttributeEnum.CONTENT.getName()));
			personMessage.setTaskId(jsonObject.getLong(MessageAttributeEnum.TASK_ID.getName()));
			personMessage.setParam(jsonObject.getString(MessageAttributeEnum.PARAM.getName()));
			personMessage.setTaskPersonId(jsonObject.getLong(MessageAttributeEnum.TASK_PERSON_ID.getName()));
			personMessage.setReadStatus(0);

			allPersonMessage.add(personMessage);
		});
		personMessageService.saveBatch(allPersonMessage);
	}
}
