package com.cyksj.service.mail.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.common.util.Jsons;
import com.cyksj.common.util.StringUtil;
import com.cyksj.common.util.TicketCodeCommonUtil;
import com.cyksj.mapper.CuiQiuEmailConfigMapper;
import com.cyksj.model.dto.CuiQiuEmailDetailDto;
import com.cyksj.model.dto.CuiQiuEmailDto;
import com.cyksj.model.dto.CuiQiuEmailResultDto;
import com.cyksj.model.entity.CuiQiuEmailConfig;
import com.cyksj.service.mail.CuiQiuMailService;
import com.cyksj.service.relation.GroupsRelationNetflixService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 项目名: yhlxj2
 * 文件名: CuiQiuMailServiceImpl
 * 创建者: JavaZou
 * 创建时间:2024/4/25 15:57
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class CuiQiuMailServiceImpl implements CuiQiuMailService {
	private final GroupsRelationNetflixService groupsRelationNetflix;

	private final static String CUI_QIU_TOKEN = "4ff0341ebf1747cd89a2d1a5a296b68b";

	//脆球域名id
	private final static String DOMAIN_ID = "1696913058045050661";

	private static List<CuiQiuEmailConfig> CuiQiuEmailConfigs;

	private final CuiQiuEmailConfigMapper CuiQiuEmailConfigMapper;

	@PostConstruct
	public void getCuiQiuEmailConfig() {
		CuiQiuEmailConfigs = CuiQiuEmailConfigMapper.selectList(null);
	}

	/**
	 * @param type              1:奈飞安全码
	 * @param linkType          链接 1：同步验证链接
	 * @param isReturnDeviceUrl true 直接返回同步装置url
	 */
	@Override
	public String getVerifyCode(String email, String relateEmail, Long goodsId, Integer type, Integer linkType, Boolean isReturnDeviceUrl) throws Exception {
		//获取近十封邮件
		String url = "https://domain-open-api.cuiqiu.com/v1/message/list";

		Map<String, Object> params = new HashMap<>();

		//获取近五分钟的代收邮件
		//维度是天
		DateTime now = DateTime.now();
		params.put("token", CUI_QIU_TOKEN);
		//关联邮件域名
		String mailId = getAdmainMailId(StrUtil.isNotEmpty(relateEmail) ? relateEmail : email);
		if (StrUtil.isEmpty(mailId)) {
			throw BusinessRuntimeException.getInstance("系统异常，请联系客服..");
		}
		params.put("mail_id", mailId);
		params.put("start_time", DateUtil.offsetDay(now, -1).toDateStr());
		params.put("end_time", DateUtil.offsetDay(now, 1).toDateStr());
		params.put("to", email);
		params.put("limit", 10);

		HttpRequest post = HttpUtil.createPost(url);
		post.form(params);
		HttpResponse execute = post.execute();
		CuiQiuEmailResultDto resultDto = Jsons.parseObject(execute.body(), CuiQiuEmailResultDto.class);
		if (resultDto.getData().getList() == null) {
			return null;
		}
		List<CuiQiuEmailDto> list = resultDto.getData().getList();
		//获取邮箱对应的邮件
//		list = list.stream().filter(emailInfo -> {
//			CuiQiuEmailDto.CuiQiuUser from = emailInfo.getFrom().get(0);
//			CuiQiuEmailDto.CuiQiuUser to = emailInfo.getTo().get(0);
//			CuiQiuEmailDto.CuiQiuUser cuiQiuUser = emailInfo.getTo().get(0);
//			if (StrUtil.equalsIgnoreCase(cuiQiuUser.getAddress(), email)) {
//				String toEmail = to.getAddress();
//				//通过直达邮件判断
//				if (StrUtil.equals(toEmail, email) || StrUtil.equals(toEmail, relateEmail)) {
//					//PS
//					if (Constant.PS_GIDS.contains(goodsId) && from.getName().contains(Constant.PS_ADOBE)) {
//						return true;
//					}
//					//Disney
//					if (goodsId == Constant.DISNEY_GID && from.getName().contains(Constant.DISNEY)) {
//						return true;
//					}
//					if (goodsId == Constant.NETFLIX_GID && from.getName().contains(Constant.NETFLIX)) {
//						return true;
//					}
//				}
//			}
//			return false;
//		}).collect(Collectors.toList());

		if (CollUtil.isNotEmpty(list)) {
			for (CuiQiuEmailDto CuiQiuEmailDto : list) {
				Long messageId = CuiQiuEmailDto.getId();
				try {
					String code = getVerifyCodeByEmail(messageId, goodsId, type, linkType, mailId, isReturnDeviceUrl);
					if (StrUtil.isNotBlank(code)) {
						return code;
					}
				} catch (Exception e) {
				}
			}
		}
		throw BusinessRuntimeException.getInstance("未收到对应邮件");
	}

	@Override
	public boolean isCuiQiuEmail(String account) {
		for (CuiQiuEmailConfig CuiQiuEmailConfig : CuiQiuEmailConfigs) {
			if (account.contains(CuiQiuEmailConfig.getDomainPrefix())) {
				return true;
			}
		}
		return false;
	}

	public String getVerifyCodeByEmail(Long messageId, Long goodsId, Integer type, Integer linkType, String mailId, Boolean isReturnDeviceUrl) throws Exception {
		String url = "https://domain-open-api.cuiqiu.com/v1/message/detail";
		Map<String, Object> params = new HashMap<>();
		params.put("token", CUI_QIU_TOKEN);
		params.put("mail_id", mailId);
		params.put("message_id", messageId);
		HttpRequest post = HttpUtil.createPost(url);
		post.form(params);
		HttpResponse execute = post.execute();
		String respBody = execute.body();
		CuiQiuEmailDetailDto CuiQiuEmailDetailDto = Jsons.parseObject(respBody, CuiQiuEmailDetailDto.class);
		CuiQiuEmailDetailDto.Content content = CuiQiuEmailDetailDto.getData().getContent();
		String code = null;
		String body = content.getBody();
		if (goodsId == 1) {
			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("查询失败，请检查是否发送了登陆码..");
				}
				int length = 4;
				return StringUtil.getVerifyCodePattern(code, length);
			} 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;
			}
		}
		if (StrUtil.isEmpty(code)) {
			code = TicketCodeCommonUtil.getTicketCodeStr(body, goodsId);
		}
		if (StrUtil.isEmpty(code)) {
			throw BusinessRuntimeException.getInstance("请重新发送对应邮件");
		}
		return code;
	}

	/**
	 * 获取接受邮件邮箱id
	 */
	private String getAdmainMailId(String email) {
		for (CuiQiuEmailConfig CuiQiuEmailConfig : CuiQiuEmailConfigs) {
			if (email.contains(CuiQiuEmailConfig.getDomainPrefix())) {
				return CuiQiuEmailConfig.getMailId();
			}
		}
		return null;
	}
}
