package org.jeecg.modules.demo.adsaccount.xxljob;

import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.demo.adsaccount.entity.AdsAccount;
import org.jeecg.modules.demo.adsaccount.service.IAdsAccountService;
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.List;

/**
 * 示例不带参定时任务
 *
 * @Author Scott
 */
@Slf4j
public class SendPendingAdsAccount implements Job {

	@Autowired
	private IAdsAccountService adsAccountService;
	@Autowired
	private ISysBaseAPI sysBaseAPI;

	@Override
	public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
		log.info("Job Execution key：" + jobExecutionContext.getJobDetail().getKey());
		log.info("Jeecg-Boot 普通定时任务：发送所有reviewStatus为pending的广告账户信息! 时间: " + DateUtils.getTimestamp());

		// 获取所有 reviewStatus 为 pending 的 AdsAccount 对象
		List<AdsAccount> pendingAdsAccounts = getPendingAdsAccounts();

		if (pendingAdsAccounts.isEmpty()) {
			log.info("没有找到 reviewStatus 为 pending 的广告账户");
		} else {
			// 将所有符合条件的广告账户信息合并成一个字符串
			StringBuilder adsAccountInfo = new StringBuilder();
			adsAccountInfo.append("有待审核的AdsAccount：\n");

			for (AdsAccount adsAccount : pendingAdsAccounts) {
				adsAccountInfo.append("\n")
						.append("账号名: ").append(adsAccount.getAccountName()).append("\n")
						.append("创建时间: ").append(adsAccount.getCreatedAt()).append("\n")
						.append("--------------------\n");
			}

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

	// 这个方法负责发送消息到飞书
	private void sendMessageToFeishu(String messageContent) throws Exception {
		// Webhook URL (替换为你实际的 Webhook URL)
//		String webhookUrl = "https://open.feishu.cn/open-apis/bot/v2/hook/14132c82-bafe-48ce-8c06-69de369d5287";
		String webhookUrl = getFeishuWebhookUrl();

		String escapeMessage = escapeSpecialCharacters(messageContent);
		// 创建 JSON Payload，包含广告账户信息
		String jsonPayload = "{ \"msg_type\": \"text\", \"content\": { \"text\": \"" + escapeMessage + "\" }}";

		// 打印 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 pending AdsAccount reviewStatus 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 pending AdsAccount reviewStatus to FeiShu group. Response code: {}, Response body: {}", responseCode, responseBody.toString());
		}

		connection.disconnect();
	}

	private List<AdsAccount> getPendingAdsAccounts() {
		// 查询 reviewStatus 为 pending 的广告账户
		return adsAccountService.getPendingReviewStatusAdsAccounts("PENDING_REVIEW");
	}

	public static String escapeSpecialCharacters(String message) {
		if (message == null) {
			return null;
		}
		// 这里将换行符转义成 \\n
		return message.replace("\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_PENDING_ADSACCOUNT".equals(dictItem.getValue())) {
					// 获取对应的 Webhook URL
					webhookUrl = dictItem.getText(); // 假设 webhook URL 存储在 text 字段中
					break; // 找到后跳出循环
				}
			}
		}
		return webhookUrl;
	}
}
