package org.springblade.mpush.timedTask;

import com.alibaba.fastjson.JSONObject;
import com.mpush.api.push.*;
import jakarta.annotation.PostConstruct;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springblade.command.feign.FzyjClient;
import org.springblade.command.pojo.vo.FzyjVO;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.tool.api.R;
import org.springblade.mpush.pojo.entity.MessagePushHistoryEntity;
import org.springblade.mpush.pojo.vo.MessagePushHistoryVO;
import org.springblade.mpush.pojo.vo.MessageVO;
import org.springblade.mpush.pojo.vo.NotificationVO;
import org.springblade.mpush.service.IMpushService;
import org.springblade.system.feign.IUserClient;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

/**
 * 消息推送 定时任务
 */
@Configuration
@EnableScheduling
@AllArgsConstructor
@Slf4j
public class MPushTask extends BladeController {

	private FzyjClient fzyjClient;

	private IUserClient userClient;

	private IMpushService mpushService;

	private static PushSender sender;

	@PostConstruct
	private void init() {
		sender = PushSender.create();
		sender.start().join();
		log.info("mpush推送服务初始化...");
	}

	/**
	 * 每1分钟 推送预警数据
	 */
	@Scheduled(cron = "0 0/1 * * * ? ")
	private void pushFzyj() {
		// 先获取未推送过的预警  预警编号 及 单位编码 , 根据单位编码排序(重要)！！！
		R<List<FzyjVO>> result = fzyjClient.getUnpushedFzyj();
		List<FzyjVO> fzyjList = result.getData();
		// 根据单位编码获取userId集合
		Long deptId = 0L;
		List<String> userIds = new ArrayList<>();
//		Logs.init();
//		PushSender sender = PushSender.create();
//		sender.start().join();
		for (FzyjVO fzyj : fzyjList) {
			if (!deptId.equals(fzyj.getDeptId())) {
				deptId = fzyj.getDeptId();
				userIds.clear();
				// 获取userId集合
				userIds = userClient.getIdByDeptId(deptId).getData();
			}
			mPush(fzyj, userIds);
			// 将预警状态修改为已推送
//			fzyjClient.updatePushStatus(fzyj.getSyncId());
		}
	}

	/**
	 * 每1分钟 推送指派数据
	 */
	@Scheduled(cron = "0 0/1 * * * ? ")
	private void pushFzyjUser() {
		// 先获取未推送过的预警  预警编号 及 单位编码 , 根据单位编码排序(重要)！！！
		R<List<FzyjVO>> result = fzyjClient.getUnpushedZp();
		List<FzyjVO> fzyjList = result.getData();
		// 根据单位编码获取userId集合
		List<String> userIds = new ArrayList<>();
//		Logs.init();
//		PushSender sender = PushSender.create();
//		sender.start().join();
		for (FzyjVO fzyj : fzyjList) {
			userIds.add(fzyj.getUserId().toString());
			mPush(fzyj, userIds);
			// 将预警状态修改为已推送
			fzyjClient.updateZpPushStatus(fzyj.getSyncId());
			userIds.clear();
		}
	}

	/**
	 * 每1分钟 失败重推
	 */
	@Scheduled(cron = "0 0/1 * * * ? ")
	private void pushAgain() {
		List<MessagePushHistoryVO> msgList =mpushService.getFailedPush();
		List<String> userIds = new ArrayList<>();
		String messageId = "";
		FzyjVO fzyj	= new FzyjVO();
		for (int i = 0; i < msgList.size(); i++) {
			// messageId与上个循环不同，推送上个循环的内容
			if (!msgList.get(i).getMessageId().equals(messageId) && StringUtils.isNotBlank(messageId)) {
				mPush(fzyj, userIds);
				userIds.clear();
			}
			userIds.add(msgList.get(i).getToUserId().toString());
			fzyj.setSyncId(Long.valueOf(msgList.get(i).getMessageId()));
			fzyj.setWarnNumber(msgList.get(i).getWarnNumber());
			fzyj.setWarnAccount(msgList.get(i).getWarnAccount());
			fzyj.setVictimName(msgList.get(i).getVictimName());
			if (i == msgList.size() - 1) {
				// 当前是最后一次循环
				mPush(fzyj, userIds);
			}
		}
	}

	private void mPush(FzyjVO fzyj, List<String> userIds) {
		try {
			// 推送消息
			Thread.sleep(1000);
			NotificationVO notification = new NotificationVO();
			notification.setTitle("反诈预警信息");
			notification.setContent("预警账号: " + fzyj.getWarnAccount() + "  受害人姓名: " + fzyj.getVictimName() == null? "暂无" : fzyj.getVictimName());
			notification.setNid(fzyj.getSyncId().intValue());
			notification.setExtras(new MessageVO(1811669161420562433L, 1811669515281408001L, fzyj.getWarnNumber(), fzyj.getSyncId(), new Date()));
			PushMsg msg = PushMsg.build(MsgType.MESSAGE, JSONObject.toJSONString(notification));
			msg.setMsgId(fzyj.getSyncId().toString());
			PushContext context = PushContext.build(msg)
				.setAckModel(AckModel.AUTO_ACK)
//						.setUserId("user-" + i)
				.setBroadcast(false)
				//.setTags(Sets.newHashSet("test"))
				//.setCondition("tags&&tags.indexOf('test')!=-1")
				.setUserIds(userIds)
				.setTimeout(2000)
				.setCallback(new PushCallback() {
					@Override
					public void onResult(PushResult result) {
						log.info("电诈预警推送结果" + JSONObject.toJSONString(result));
						switch (result.resultCode) {
							// 保存日志
							case 1:
								mpushService.save(new MessagePushHistoryEntity(1, fzyj.getSyncId().toString(), Long.valueOf(result.userId), 1));
								break;
							case 2:
								mpushService.save(new MessagePushHistoryEntity(1, fzyj.getSyncId().toString(), Long.valueOf(result.userId), 2));
								break;
							case 3:
								mpushService.save(new MessagePushHistoryEntity(1, fzyj.getSyncId().toString(), Long.valueOf(result.userId), 3));
								break;
							case 4:
								mpushService.save(new MessagePushHistoryEntity(1, fzyj.getSyncId().toString(), Long.valueOf(result.userId), 4));
						}
					}
				});
			sender.send(context);
			// 暂停1秒钟
			LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(1));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
