package com.cyksj.service.mail.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.cyksj.common.constant.Constant;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.common.util.StringUtil;
import com.cyksj.common.util.TicketCodeCommonUtil;
import com.cyksj.service.mail.MailLuService;
import com.cyksj.service.relation.GroupsRelationNetflixService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.mail.*;
import javax.mail.search.AndTerm;
import javax.mail.search.ComparisonTerm;
import javax.mail.search.ReceivedDateTerm;
import javax.mail.search.SearchTerm;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Properties;

/**
 * 项目名: yhlxj2
 * 文件名: MailLuServiceImpl
 * 创建者: JavaZou
 * 创建时间:2024/12/23 11:14
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class MailLuServiceImpl implements MailLuService {
	//mail lu邮箱统一密码
	private final static String UNIFIED_PWD = "Wp112233";

	private final GroupsRelationNetflixService groupsRelationNetflix;

	@Override
	public boolean isMailLuEmail(String account) {
		for (String domain : Constant.MAIL_LU_DOMAIN) {
			if (account.contains(domain)) {
				return true;
			}
		}
		return false;
	}

	@Override
	public String getVerifyCode(String account, String relateEmail, Long goodsId, Integer type, Integer linkType, boolean isReturnDeviceUrl) throws Exception {
		Properties props = new Properties();
		props.put("mail.imap.host", "mail.yxzh8.com"); // 替换为你的IMAP服务器
		props.put("mail.imap.port", "993"); // IMAP服务的端口号，通常是993
		props.put("mail.imap.ssl.enable", "true"); // 启用SSL

		Session session = Session.getInstance(props, new javax.mail.Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(StrUtil.isNotBlank(relateEmail) ? relateEmail : account, UNIFIED_PWD);
			}
		});

		Store store = session.getStore("imap");
		store.connect();
		// 访问收件箱
		Folder inbox = store.getFolder("INBOX");
		inbox.open(Folder.READ_ONLY);
		// 设置时间范围
		DateTime now = DateTime.now();
		//10分钟
		DateTime differ = DateUtil.offsetMinute(now, -10);
		// 构建搜索条件
		SearchTerm searchTerm = new AndTerm(
				new ReceivedDateTerm(ComparisonTerm.GE, differ),
				new ReceivedDateTerm(ComparisonTerm.LE, now)
		);

		// 执行搜索
		Message[] messages = inbox.search(searchTerm);
		// 根据接收日期对邮件进行排序
		Arrays.sort(messages, new Comparator<Message>() {
			public int compare(Message m1, Message m2) {
				try {
					return m2.getReceivedDate().compareTo(m1.getReceivedDate());
				} catch (MessagingException e) {
					log.error("将邮件按时间排序错误:{}", StringUtil.getErrorText(e));
					throw BusinessRuntimeException.getInstance("获取异常，请联系客服");
				}
			}
		});
		String code = null;
		for (int i = 0; i < messages.length; i++) {
			Message message = messages[i];
			//主题
			String subject = message.getSubject();
			//content
			String body = message.getContent().toString();
			if (goodsId == 1 && subject.contains(Constant.NETFLIX)) {
				if (type != null && type == 1) {
					String pre = "NetflixSans-Regular, Helvetica, Roboto, Segoe UI, sans-serif; font-weight";
					if (body.contains("輸入此代碼登入") || body.contains("输入此代码登录") || body.contains("Enter this code to sign in")) {
						code = StrUtil.subAfter(body, pre, false);
						if (StrUtil.isEmpty(code)) {
							code = StrUtil.subAfter(body, "Enter this code to sign in", true);
						}
						if (StrUtil.isEmpty(code)) {
							code = StrUtil.subAfter(body, "font-weight: 400; color: #232323; padding-top: 20px;", true);
						}
					}
					if (StrUtil.isEmpty(code)) {
						throw BusinessRuntimeException.getInstance("查询失败，请检查是否发送了登陆码..");
					}
				} else {
					String urlPref;
					String nfVerifyUrl;
					if (linkType == 1) {
						urlPref = "https://www.netflix.com/account/update-primary-location";
						nfVerifyUrl = TicketCodeCommonUtil.extractUrl(body, urlPref);
					} else {
						urlPref = "https://www.netflix.com/account/travel/verify";
						nfVerifyUrl = TicketCodeCommonUtil.extractUrl(body, urlPref);
					}
					if (StrUtil.isEmpty(nfVerifyUrl)) {
						throw BusinessRuntimeException.getInstance("请在奈飞端点击“传送电子邮件”");
					}
					//非点击装置同步更新按钮 直接返回链接
					if (linkType == 2) return nfVerifyUrl;
					//直接返回同步装置url
					if (isReturnDeviceUrl) {
						return nfVerifyUrl;
					}
					//失败返回验证链接
					if (!groupsRelationNetflix.confirmUpdate(nfVerifyUrl)) {
						return nfVerifyUrl;
					}
					return StrUtil.EMPTY;
				}
			}
			//PS、Disney
			code = TicketCodeCommonUtil.getTicketCodeStr(body, goodsId);
			if (code != null) {
				return code;
			}
		}
		inbox.close(false);
		store.close();
		if (StrUtil.isEmpty(code)) {
			throw BusinessRuntimeException.getInstance("请重新发送对应邮件");
		}
		return code;
	}
}
