package org.jeecg.modules.quartz.job;

import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.aspect.annotation.Dict;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.userLogin.entity.UserLogin;
import org.jeecg.modules.userLogin.service.IUserLoginService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.List;

@Slf4j
public class SendNewRegisterLeads implements Job {

	@Autowired
	private IUserLoginService userLoginService;
	@Autowired
	private ISysBaseAPI sysBaseAPI;

	@Override
	public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
		log.info("Job Execution key：" + jobExecutionContext.getJobDetail().getKey());
		log.info(String.format("Jeecg-Boot 普通定时任务 飞书机器人发送新注册的canary用户! 时间: " + DateUtils.getTimestamp()));

		// 获取前一小时内注册的 UserLogin 对象
		List<UserLogin> recentUserLogins = getRecentUserLogins();

		if (recentUserLogins.isEmpty()) {
			log.info("最近一小时没有新注册客户");
		} else {
			// 将所有新注册用户的信息合并成一个字符串
			StringBuilder userInfo = new StringBuilder();
			userInfo.append("最近一小时内出现了新注册的Canary用户：\n");

			for (UserLogin userLogin : recentUserLogins) {
				userInfo.append("\n")
						.append("用户名: ").append(userLogin.getUsername()).append("\n")
						.append("公司: ").append(userLogin.getCompany()).append("\n")
						.append("电话: ").append(userLogin.getMobile()).append("\n")
						.append("--------------------\n");
			}

			// 发送合并的消息到飞书
			try {
				sendMessageToFeishu(userInfo.toString());
			} catch (Exception e) {
				log.info("发送消息失败", e);
			}
		}
	}

	// 这个方法负责发送消息到飞书
	private void sendMessageToFeishu(String messageContent) throws Exception {
		// 处理消息内容中的特殊字符
		String escapedMessage = escapeSpecialCharacters(messageContent);
		// Webhook URL (替换为你实际的 Webhook URL)
//		String webhookUrl = "https://open.feishu.cn/open-apis/bot/v2/hook/75f88884-8a99-4531-bdee-3a148e0fa782";
		String webhookUrl = getFeishuWebhookUrl();

		// 创建 JSON Payload，包含用户信息
		String jsonPayload = "{ \"msg_type\": \"text\", \"content\": { \"text\": \"" + escapedMessage + "\" }}";

		// 打印 JSON Payload 格式以进行调试
		log.info("Payload: {}", jsonPayload);

		// 发送 JSON Payload 到飞书通过 HTTP POST
		URL url = new URL(webhookUrl);
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setRequestMethod("POST");
		connection.setRequestProperty("Content-Type", "application/json");
		connection.setDoOutput(true);

		try (OutputStream os = connection.getOutputStream()) {
			byte[] input = jsonPayload.getBytes("utf-8");
			os.write(input, 0, input.length);
		}

		// 获取响应码和响应体
		int responseCode = connection.getResponseCode();
		StringBuilder responseBody = new StringBuilder();

		// 如果是 200 OK，读取正常响应体
		if (responseCode == HttpURLConnection.HTTP_OK) {
			try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
				String inputLine;
				while ((inputLine = in.readLine()) != null) {
					responseBody.append(inputLine);
				}
			}
			log.debug("Successfully sent new user login leads to FeiShu group. Response code: {}, Response body: {}", responseCode, responseBody.toString());
		} else {
			// 如果是其他响应码，读取错误响应体
			try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getErrorStream()))) {
				String inputLine;
				while ((inputLine = in.readLine()) != null) {
					responseBody.append(inputLine);
				}
			}
			log.error("Failed to send new user login leads to FeiShu group. Response code: {}, Response body: {}", responseCode, responseBody.toString());
		}

		connection.disconnect();
	}

	private List<UserLogin> getRecentUserLogins() {
		Date currentTime = new Date();
		long oneHourAgoMillis = currentTime.getTime() - 3600000; // 毫秒级时间戳
		Date oneHourAgo = new Date(oneHourAgoMillis); // 转换为 Date 对象
		return userLoginService.getUserLoginsByRegistrationTime(oneHourAgo);
	}

	// 用于处理特殊字符的转义方法
	public static String escapeSpecialCharacters(String message) {
		if (message == null) {
			return null;
		}
		return message.replace("\n", "\\n");  // 这里保持换行符为 \\n
	}

	public String getFeishuWebhookUrl() {
		List<DictModel> dictItems = sysBaseAPI.getDictItems("feishu_bot");
		String webhookUrl = null;
		if (dictItems != null && !dictItems.isEmpty()) {
			for (DictModel dictItem : dictItems) {
				if ("NEW_REGIDSTER".equals(dictItem.getValue())) {
					// 获取对应的 Webhook URL
					webhookUrl = dictItem.getText(); // 假设 webhook URL 存储在 text 字段中
					break; // 找到后跳出循环
				}
			}
		}
		return webhookUrl;
	}
}
