package com.cyksj.service.mail.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.common.util.StringUtil;
import com.cyksj.common.util.TicketCodeCommonUtil;
import com.cyksj.mapper.sys.SysEmailMapper;
import com.cyksj.model.entity.SysEmail;
import com.cyksj.service.mail.YhMailService;
import com.cyksj.service.relation.GroupsRelationNetflixService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 项目名: yhlxj2
 * 文件名: YhEmailServiceImpl
 * 创建者: JavaZou
 * 创建时间:2024/8/19 15:40
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class YhEmailServiceImpl implements YhMailService {
	private final GroupsRelationNetflixService groupsRelationNetflixService;

	private final SysEmailMapper sysEmailMapper;

	@Override
	public String getVerifyCode(String account, String relateEmail, Long goodsId, Integer type, Integer linkType, Boolean isReturnDeviceUrl) throws Exception {
		String body = readEmail(StrUtil.isNotEmpty(relateEmail) ? relateEmail : account);
		String code = getDifferentGoodsCode(goodsId, body, type, linkType, isReturnDeviceUrl);
		if (StrUtil.isEmpty(code)) {
			throw BusinessRuntimeException.getInstance("请重新发送对应邮件");
		}
		return code;
	}

	@Override
	public String readResetPwdResetLink(String account) {
		String body = readEmail(account);
		String prefix = "https://auth0.openai.com/u/reset-verify";
		if (body.contains(prefix)) {
			String query = StrUtil.subBetween(body, "<" + prefix, ">");
			if(StringUtils.isBlank(query)){
				query = StrUtil.subBetween(body, "(" + prefix, ")");
				if(StringUtils.isBlank(query)){
					query = StrUtil.subBetween(body, "( " + prefix, " )");
				}
			}
			String link = prefix + query;
			if (link.contains("\uE53B")) {
				link = link.replace("\uE53B", "=");
			}
			if (!link.contains("=")) {
				link = link.replaceAll("(ticket)[^=]", "$1=");
			}
			return link;
		}
		throw BusinessRuntimeException.getInstance("读取重置密码邮件失败或被新邮件覆盖");
	}

	@Override
	public String getGptCode(String account) {
		String body = readEmail(account);
		String prefix = "Enter this temporary verification";
		if (body.contains(prefix)) {
			String str = StrUtil.subAfter(body, prefix, true);
			String code = StringUtil.getVerifyCodePattern(str, 6);
			return code;
		}
		throw BusinessRuntimeException.getInstance("获取验证码失败或被新邮件覆盖");
	}

	public String readEmail(String account) {
		//获取邮箱密码
		SysEmail sysEmail = sysEmailMapper.selectOne(Wrappers.lambdaQuery(SysEmail.class)
				.eq(SysEmail::getEmail, account)
				.last("limit 1"));
		if (sysEmail == null) {
			log.info("获取账号：{}验证码异常,未配置对应系统邮箱", account);
			throw BusinessRuntimeException.getInstance("对应邮箱配置不存在...");
		}
		String url = "http://yinhelx.com/api/controller.php";
		Map<String, Object> params = new HashMap<>();

		params.put("imap_key", "imap_56568niua@@");
		params.put("fun", "imap_read");
		params.put("imap_ip", "yinhelx.com");
		params.put("port", "143");
		params.put("username", account);
		params.put("password", sysEmail.getPassword());
		params.put("mbox_id", "0");
		params.put("delete", "0");

		HttpRequest post = HttpUtil.createPost(url);
		post.form(params);
		cn.hutool.http.HttpResponse execute = post.execute();
		if (execute.getStatus() != HttpStatus.HTTP_OK) {
			throw BusinessRuntimeException.getInstance("获取验证码异常,请联系客服...");
		}
		return execute.body();
	}

	public String getDifferentGoodsCode(Long goodsId, String body, Integer type, Integer linkType, Boolean isReturnDeviceUrl) {
		String code = null;
		//奈飞
		if (goodsId == 1) {
			if (type != null && type == 1) {
				if (body.contains("輸入此代碼登入") || body.contains("输入此代码登录") || body.contains("Enter this code to sign in")) {
					code = StrUtil.subBetween(body, "輸入此代碼登入", "請在裝置上輸入上");
					if (StrUtil.isEmpty(code)) {
						code = StrUtil.subAfter(body, "输入此代码登录", true);
					}
					if (StrUtil.isEmpty(code)) {
						code = StrUtil.subAfter(body, "Enter this code to sign in", true);
					}
				}
				if (StrUtil.isEmpty(code)) {
					throw BusinessRuntimeException.getInstance("查询失败，请检查是否发送了登陆码..");
				}
			} else {
				String urlPref;
				//更新装置
				if (linkType == 1) {
					urlPref = "https://www.netflix.com/account/update-primary-location";
					code = StrUtil.subBetween(body, "[" + urlPref, "]");
				} else {
					//验证链接
					urlPref = "https://www.netflix.com/account/travel/verify";
					code = StrUtil.subBetween(body, "[" + urlPref, "]");
				}
				if (StrUtil.isEmpty(code)) {
					throw BusinessRuntimeException.getInstance("请在奈飞端点击“传送电子邮件”");
				}
				String url = urlPref + code;
				//非点击装置同步更新按钮 直接返回链接
				if (linkType == 2) return url;
				//直接返回同步更新装置url
				if (isReturnDeviceUrl) {
					return url;
				}
				//失败返回验证链接
				if (!groupsRelationNetflixService.confirmUpdate(url)) {
					return url;
				}
				return StrUtil.EMPTY;
			}
		}
		//除奈飞
		if (StrUtil.isEmpty(code)) {
			code = TicketCodeCommonUtil.getTicketCodeStr(body, goodsId);
		}
		return code;
	}

}
