package org.jeecg.modules.adweb.enquiry.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xkcoding.http.util.StringUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.dto.message.MessageDTO;
import org.jeecg.common.constant.CacheConstant;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.enums.SysAnnmentTypeEnum;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.system.vo.DictPropertyModel;
import org.jeecg.common.util.FastJsonUtil;
import org.jeecg.modules.adweb.common.constant.NumConstant;
import org.jeecg.modules.adweb.common.dto.CountryAreaApiDto;
import org.jeecg.modules.adweb.common.service.FeishuService;
import org.jeecg.modules.adweb.common.util.*;
import org.jeecg.modules.adweb.enquiry.constant.EnquiryConstants;
import org.jeecg.modules.adweb.enquiry.constant.EnquirySendStatus;
import org.jeecg.modules.adweb.enquiry.dto.EnquiryDTO;
import org.jeecg.modules.adweb.enquiry.dto.param.EffectiveEnquiryParamDto;
import org.jeecg.modules.adweb.enquiry.dto.result.EnquirySpecialFields;
import org.jeecg.modules.adweb.enquiry.entity.*;
import org.jeecg.modules.adweb.enquiry.mapper.AdwebEnquiryMapper;
import org.jeecg.modules.adweb.enquiry.service.*;
import org.jeecg.modules.adweb.site.entity.AdwebSite;
import org.jeecg.modules.adweb.site.service.IAdwebSiteService;
import org.jeecg.modules.adweb.system.entity.SysException;
import org.jeecg.modules.adweb.system.service.IMasterSubAccountRelationService;
import org.jeecg.modules.adweb.system.service.ISysExceptionService;
import org.jeecg.modules.adweb.system.service.impl.SysAdwebApiImpl;
import org.jeecg.modules.message.handle.impl.SystemSendMsgHandle;
import org.jeecg.modules.system.entity.SysDictItem;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysDictService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @Description: 询盘信息存储表单
 * @Author: jeecg-boot
 * @Date: 2024-10-12
 * @Version: V1.0
 */
@Slf4j
@Service
public class AdwebEnquiryServiceImpl extends ServiceImpl<AdwebEnquiryMapper, AdwebEnquiry> implements IAdwebEnquiryService {

    @Resource
    private AdwebEnquiryMapper adwebEnquiryMapper;

    @Resource
    @Lazy
    private ISysUserService sysUserService;

    @Resource
    private IMasterSubAccountRelationService masterSubAccountRelationService;

    @Resource
    private GeoIpUtil geoIpUtil;

    @Resource
    private IAdwebPublicEnquiryRuleService AdwebPublicEnquiryRuleService;

    @Resource
    private ISysDictService dictService;

    @Resource
    private SnowflakeIdUtil snowflakeIdUtil;

    @Resource
    private AdwebRedisUtil adwebRedisUtil;

    @Resource
    private ISysExceptionService sysExceptionService;

    @Resource
    private FeishuService feishuService;

    @Resource
    private IAdwebEnquiryBlacklistService adwebEnquiryBlacklistService;

    @Resource
    private IAdwebSiteBlackEmailService enquirySiteBlackEmailService;

    @Resource
    private IAdwebPublicBlackEmailService adwebPublicBlackEmailService;

    @Resource
    private IAdwebPublicBlackIpService adwebPublicBlackIpService;

    @Resource
    private IAdwebSiteBlackIpService adwebSiteBlackIpService;

    @Resource
    private IAdwebSiteEnquiryRuleService adwebSiteEnquiryRuleService;

    @Resource
    private IEnquiryEmailMessageService enquiryEmailMessageService;

    @Resource
    private IAdwebSiteService adwebSiteService;

    @Resource
    private AdwebOpenApiService adwebOpenApiService;

    @Resource
    private IAdwebEnquiryFormService adwebEnquiryFormService;

    @Resource
    private SysAdwebApiImpl sysAdwebApiImpl;

    @Resource
    private SystemSendMsgHandle systemSendMsgHandle;

    private static final byte[] redisKey = EnquiryConstants.ENQUIRY_EMAIL.getBytes();

    private static final byte[] siteRedisKey = EnquiryConstants.ENQUIRY_SITE.getBytes();

    // Email Redis key
    private static final String EmailTenMinKey = "JUDGE_WASTE_ENQUIRY_EMAIL_BY_10_MIN::";
    private static final String EmailOneDayKey = "JUDGE_WASTE_ENQUIRY_EMAIL_BY_ONE_DAY::";
    private static final String BlackEmailKey = "BLACK_EMAIL_LIST";
    private static final String WhiteEmailListKey = "WHITE_EMAIL_LIST";
    private static final String NotBlackEmailWasteEnquiryKey = "NOT_BLACK_EMAIL_WASTE_ENQUIRY_MAP::";

    // site Email Redis key
    private static final String SiteEmailTenMinKey = "JUDGE_WASTE_SITE_ENQUIRY_EMAIL_BY_10_MIN::";
    private static final String SiteEmailOneDayKey = "JUDGE_WASTE_SITE_ENQUIRY_EMAIL_BY_ONE_DAY::";
    private static final String SiteBlackEmailKey = "SITE_BLACK_EMAIL_LIST";
    private static final String SiteWhiteEmailListKey = "SITE_WHITE_EMAIL_LIST";
    private static final String NotBlackEmailWasteSiteEnquiryKey = "NOT_BLACK_EMAIL_WASTE_SITE_ENQUIRY_MAP::";

    //ip Reids Key
    private static final String IpTenMinKey = "JUDGE_WASTE_ENQUIRY_IP_BY_10_MIN::";
    private static final String IpOneDayKey = "JUDGE_WASTE_ENQUIRY_IP_BY_ONE_DAY::";
    private static final String BlackIpKey = "BLACK_IP_LIST";
    private static final String WhiteIpListKey = "WHITE_IP_LIST";
    private static final String NotBlackIpWasteEnquiryKey = "NOT_BLACK_IP_WASTE_ENQUIRY_MAP::";

    //site ip Reids Key
    private static final String SiteIpTenMinKey = "JUDGE_WASTE_ENQUIRY_SITE_IP_BY_10_MIN::";
    private static final String SiteIpOneDayKey = "JUDGE_WASTE_ENQUIRY_SITE_IP_BY_ONE_DAY::";
    private static final String NotSiteBlackIpWasteEnquiryKey = "NOT_SITE_BLACK_IP_WASTE_ENQUIRY_MAP::";
    private static final String SiteBlackIpKey = "SITE_BLACK_IP_LIST";
    private static final String SiteWhiteIpListKey = "SITE_WHITE_IP_LIST";

    @Value("${judge_waste_enquiry.email.tenMinNum}")
    private Integer emailTenMinNum;
    @Value("${judge_waste_enquiry.email.oneDayNum}")
    private Integer emailOneDayNum;
    @Value("${judge_waste_enquiry.ip.tenMinNum}")
    private Integer ipTenMinNum;
    @Value("${judge_waste_enquiry.ip.oneDayNum}")
    private Integer ipOneDayNum;
    @Value("${judge_waste_enquiry.email.notBlackListNum}")
    private Integer emailNotBlackListNum;
    @Value("${judge_waste_enquiry.ip.notBlackListNum}")
    private Integer ipNotBlackListNum;
    @Value("${judge_waste_enquiry.email.notBlackListDate}")
    private Integer emailNotBlackListDate;
    @Value("${judge_waste_enquiry.ip.notBlackListDate}")
    private Integer ipNotBlackListDate;

    // 获取有效公共询盘规则
    private List<String> getPublicEnquiryRules(int blackOrWhite, int useStatus) {

        List<String> blackWordList = null;
        try {
            List<AdwebPublicEnquiryRule> AdwebPublicEnquiryRuleList = AdwebPublicEnquiryRuleService.list(new LambdaQueryWrapper<AdwebPublicEnquiryRule>()
                    .eq(AdwebPublicEnquiryRule::getStatus, 1)
                    .eq(AdwebPublicEnquiryRule::getIsEnable, 1)
                    .eq(AdwebPublicEnquiryRule::getBlackOrWhiteList, blackOrWhite)
                    .eq(AdwebPublicEnquiryRule::getUseStatus, useStatus));
            if (CollectionUtils.isNotEmpty(AdwebPublicEnquiryRuleList)) {
                blackWordList = AdwebPublicEnquiryRuleList.stream().map(AdwebPublicEnquiryRule::getWord).toList();
            }
        } catch (Exception e) {
            log.error("读取询盘黑名单关键词失败", e);
        }

        return blackWordList;
    }

    /**
     * 添加询盘
     *
     * @param enquiryDto 询盘对象
     * @return
     */
    public void addEnquiry(EnquiryDTO enquiryDto, String plugin, List<AdwebSite> adwebSites) {

        // 获取公共黑名单关键词
        List<String> blackWordList = getPublicEnquiryRules(0, 0);

        AdwebSite adwebSite = adwebSites.get(0);

        //获取子账户
        Map<String, String> principalEmailMap = new HashMap<>();
        List<String> subAccountIdList = masterSubAccountRelationService.getSubAccountIdByMaster(String.valueOf(adwebSite.getUid()));
        log.info("获取的子账户id：{}", FastJsonUtil.toJSONString(subAccountIdList));
        if (CollectionUtils.isNotEmpty(subAccountIdList)) {
            subAccountIdList.add(String.valueOf(adwebSite.getUid()));
            List<SysUser> principalEmailList = sysUserService.list(new QueryWrapper<SysUser>().in("id", subAccountIdList).eq("del_flag", 0).isNotNull("email").ne("email", "").select("id", "email"));
            if (CollectionUtils.isNotEmpty(principalEmailList)) {
                principalEmailMap = principalEmailList.stream().collect(Collectors.toMap(SysUser::getId, SysUser::getEmail));

            }
        }

        List<AdwebEnquiry> adwebEnquiryList = new ArrayList<>();
        AdwebEnquiryForm form = new AdwebEnquiryForm();

        try {
            AdwebEnquiry adwebEnquiry = createEnquiry(enquiryDto, adwebSite);

            String forms = FastJsonUtil.toJSONString(enquiryDto.getForms());
            parseFormAndSetFields(adwebEnquiry, forms, adwebSite);
            setCountryByIp(adwebEnquiry);

            adwebEnquiryList.add(adwebEnquiry);


            form.setEnquiryId(adwebEnquiry.getId());
            form.setForm(forms);
            form.setCountry(adwebEnquiry.getCountry());
            form.setPluginName(plugin);


        } catch (Exception e) {
            log.error("消费站点为：{}， recordId为：{} 的询盘出现问题", adwebSite.getName(), enquiryDto.getRecordId(), e);
        }

        // 公共黑名单，站点黑名单过滤
        judgeWasteEnquiryBySiteId(adwebEnquiryList, adwebSite, blackWordList);

        // 客户黑名单过滤
        judgeBlacklist(adwebEnquiryList);

        if (!adwebEnquiryList.isEmpty()) {
            try {
                AdwebEnquiry target = adwebEnquiryList.get(0);
                this.save(target);
                adwebEnquiryFormService.save(form);

                MessageDTO messageDTO = new MessageDTO();
                String title = "您已经收到询盘 ";
                messageDTO.setTitle(title);
                Map<String, Object> data = new HashMap<>();
                //update-begin---author:wangshuai---date:2024-03-11---for:【QQYUN-8425】用户导入成功后 消息提醒 跳转至同意页面---
                data.put(CommonConstant.NOTICE_MSG_BUS_TYPE, SysAnnmentTypeEnum.BPM.getType());
                //update-end---author:wangshuai---date:2024-03-11---for:【QQYUN-8425】用户导入成功后 消息提醒 跳转至同意页面---
                messageDTO.setData(data);
                messageDTO.setContent("您已经收到询盘 您已经收到询盘 您已经收到询盘 您已经收到询盘 ");
                messageDTO.setToUser("admin");
                messageDTO.setFromUser("system");
                systemSendMsgHandle.sendMessage(messageDTO);
            } catch (Exception e) {
                log.error("站点为：{}，  recordId为：{} 保存询盘到数据库失败，原因是:{}", adwebSite.getName(), enquiryDto.getRecordId(), e.getMessage());
            }

            // 发送询盘邮件
            sendValidateEmail(adwebEnquiryList, adwebSite, principalEmailMap);
        }
    }


    /**
     * 发送询盘邮件
     *
     * @param enquiryList       待发送询盘列表
     * @param adwebSite         接收邮箱集合
     * @param principalEmailMap
     */
    private void sendValidateEmail(List<AdwebEnquiry> enquiryList, AdwebSite adwebSite, Map<String, String> principalEmailMap) {
        if (CollectionUtils.isEmpty(enquiryList)) {
            log.info("未获取到需要发送邮件的询盘");
            return;
        }
        log.info("需要发送邮件的询盘：{}", FastJsonUtil.toJSONString(enquiryList));

        //特殊站点发送邮件
        List<DictPropertyModel> siteRes = sysAdwebApiImpl.queryDictInfoByDictCode("turn_inquiry_site_code");
        if (CollectionUtils.isNotEmpty(siteRes) && siteRes.get(0).getValue().equals(adwebSite.getCode())) {
            specialSendEmail(enquiryList, adwebSite);
        } else {
            String emailStr = adwebSite.getEnquiryEmailList();
            if (StringUtil.isEmpty(emailStr)) {
                log.info("未获取到站点邮箱");
                return;
            }
            log.info("发送询盘邮件--站点邮箱：{}", emailStr);
            log.info("发送询盘邮件--子账户邮箱：{}", FastJsonUtil.toJSONString(principalEmailMap));

            List<String> emailList = JSON.parseArray(emailStr, String.class);
            if (CollectionUtils.isEmpty(emailList)) {
                return;
            }


            List<EnquiryEmailMessage> enquiryEmailMessageList = new ArrayList<>();
            for (AdwebEnquiry adwebEnquiry : enquiryList) {
                if (adwebEnquiry.getWasteEnquiry() != 1 && adwebEnquiry.getStatus() != 0) {
                    HashSet<String> emailSet = new HashSet<>();
                    String priUid = adwebEnquiry.getPrincipalUid();

                    if (principalEmailMap.isEmpty()) {
                        for (String e : emailList) {
                            if (emailSet.contains(e)) {
                                continue;
                            }
                            enquiryEmailMessageList.add(newEmail(adwebEnquiry, e));
                            emailSet.add(e);
                        }
                    }
                    //1 如果选择发送全部 2.不是产品页面 全发
                    else if (StringUtil.isEmpty(adwebEnquiry.getPrincipalUid()) || adwebEnquiry.getExistProductEnquiry() == null || adwebEnquiry.getExistProductEnquiry() == 0 || adwebEnquiry.getPrincipalUid().equals("ALL")) {
                        if (adwebSite.getEnquirySendEmailType().equals("ALL")) {
                            log.info("发送询盘邮件--不是产品--进行所有账号发送规则");
                            for (String e : principalEmailMap.values()) {
                                if (emailSet.contains(e)) {
                                    continue;
                                }
                                enquiryEmailMessageList.add(newEmail(adwebEnquiry, e));
                                emailSet.add(e);
                            }
                        } else {
                            //询盘邮件规则 主账号和添加了的负责人,如果负责人选择了all取所有人
                            log.info("发送询盘邮件--不是产品--进行只有主账号发送规则--负责人不为all");
                            if (!"ALL".equals(adwebEnquiry.getPrincipalUid())) {
                                //主账号
                                SysUser masterUserAccount = sysUserService.getById(adwebEnquiry.getUid());
                                if (masterUserAccount != null && StringUtils.isNotBlank(masterUserAccount.getEmail())) {
                                    emailSet.add(masterUserAccount.getEmail());
                                    enquiryEmailMessageList.add(newEmail(adwebEnquiry, masterUserAccount.getEmail()));
                                }
                                //负责人
                                for (String key : principalEmailMap.keySet()) {
                                    if (adwebEnquiry.getPrincipalUid().equals(key) && !emailSet.contains(principalEmailMap.get(key))) {
                                        enquiryEmailMessageList.add(newEmail(adwebEnquiry, principalEmailMap.get(key)));
                                        emailSet.add(principalEmailMap.get(key));
                                    }
                                }
                            } else {
                                //判断是否走同步询盘，同步询盘不进行全部处理
                                log.info("发送询盘邮件--不是产品--进行只有主账号发送规则--负责人为all");
                                if (StringUtil.isEmpty(adwebEnquiry.getIsEnquirySync())) {
                                    for (String e : principalEmailMap.values()) {
                                        if (emailSet.contains(e)) {
                                            continue;
                                        }
                                        enquiryEmailMessageList.add(newEmail(adwebEnquiry, e));
                                        emailSet.add(e);
                                    }
                                } else {
                                    //主账号
                                    SysUser masterUserAccount = sysUserService.getById(adwebEnquiry.getUid());
                                    if (masterUserAccount != null && StringUtils.isNotBlank(masterUserAccount.getEmail())) {
                                        emailSet.add(masterUserAccount.getEmail());
                                        enquiryEmailMessageList.add(newEmail(adwebEnquiry, masterUserAccount.getEmail()));
                                    }
                                }
                            }
                        }
                        for (String e : emailList) {
                            if (emailSet.contains(e)) {
                                continue;
                            }
                            enquiryEmailMessageList.add(newEmail(adwebEnquiry, e));
                            emailSet.add(e);
                        }
                    }
                    //当主站为空
                    else if (StringUtil.isEmpty(principalEmailMap.get(adwebEnquiry.getUid())) && adwebEnquiry.getExistProductEnquiry() == 1) {
                        log.info("发送询盘邮件--产品询盘--当主站为空");
                        String email = principalEmailMap.get(priUid);
                        List<String> subSiteEmailList = null;
                        if (StringUtils.isNotBlank(email)) {
                            enquiryEmailMessageList.add(newEmail(adwebEnquiry, email));
                            emailSet.add(email);
                            //筛选出子站点，不给子站点发，给配置询盘的地方发
                            subSiteEmailList = principalEmailMap.entrySet()
                                    .stream()
                                    .filter(entry -> !email.equals(entry.getKey()))
                                    .map(Map.Entry::getValue)
                                    .collect(Collectors.toList());
                        } else {
                            subSiteEmailList = new ArrayList<>(principalEmailMap.values());
                        }


                        //遍历emailList 不包含subSiteEmailList
                        for (String e : emailList) {
                            if (subSiteEmailList.contains(e) || emailSet.contains(e)) {
                                continue;
                            }
                            enquiryEmailMessageList.add(newEmail(adwebEnquiry, e));
                            emailSet.add(e);
                        }
                    }
                    //如果当前询盘配置的为子账户 则给子账户和主账户发
                    else if (adwebEnquiry.getExistProductEnquiry() == 1 && !adwebEnquiry.getUid().equals(priUid)) {
                        log.info("发送询盘邮件--产品询盘--如果当前询盘配置的为子账户 则给子账户和主账户发");
                        String email = principalEmailMap.get(priUid);
                        if (StringUtils.isNotBlank(email)) {
                            enquiryEmailMessageList.add(newEmail(adwebEnquiry, email));
                            emailSet.add(email);
                        }

                        //给主账户发
                        String masterEmail = principalEmailMap.get(adwebEnquiry.getUid());
                        if (emailSet.contains(masterEmail)) {
                            continue;
                        }
                        enquiryEmailMessageList.add(newEmail(adwebEnquiry, masterEmail));
                        emailSet.add(masterEmail);

                        //筛选出子站点，不给子站点发，给配置询盘的地方发
                        List<String> subSiteEmailList = principalEmailMap.entrySet()
                                .stream()
                                .filter(entry -> !Arrays.asList(email, masterEmail).contains(entry.getKey()))
                                .map(Map.Entry::getValue)
                                .collect(Collectors.toList());

                        //遍历emailList 不包含subSiteEmailList
                        for (String e : emailList) {
                            if (subSiteEmailList.contains(e) || emailSet.contains(e)) {
                                continue;
                            }
                            enquiryEmailMessageList.add(newEmail(adwebEnquiry, e));
                            emailSet.add(e);
                        }
                    }
                    //如果当前询盘配置的为主账户 则只给主账户发 //还有一种情况 子账户为空 只给主站发
                    else if (adwebEnquiry.getUid().equals(priUid) && adwebEnquiry.getExistProductEnquiry() == 1) {
                        log.info("发送询盘邮件--产品询盘--如果当前询盘配置的为主账户 则只给主账户发 //还有一种情况 子账户为空 只给主站发");
                        String email = principalEmailMap.get(priUid);
                        enquiryEmailMessageList.add(newEmail(adwebEnquiry, email));
                        emailSet.add(email);

                        //筛选出子站点，不给子站点发，给配置询盘的地方发
                        List<String> subSiteEmailList = principalEmailMap.entrySet()
                                .stream()
                                .filter(entry -> !entry.getKey().equals(priUid))
                                .map(Map.Entry::getValue)
                                .collect(Collectors.toList());

                        //遍历emailList 不包含subSiteEmailList
                        for (String e : emailList) {
                            if (subSiteEmailList.contains(e) || emailSet.contains(e)) {
                                continue;
                            }
                            enquiryEmailMessageList.add(newEmail(adwebEnquiry, e));
                            emailSet.add(e);
                        }
                    }
                }
            }

            log.info("=======发送询盘邮件======");
            enquiryEmailMessageList.forEach(e -> System.out.println(e.getEmail()));
            log.info("需要添加的询盘邮件：{}", FastJsonUtil.toJSONString(enquiryEmailMessageList));
            if (CollectionUtils.isNotEmpty(enquiryEmailMessageList)) {
                QueryWrapper<EnquiryEmailMessage> enquiryEmailMessageQueryWrapper = new QueryWrapper<>();
                enquiryEmailMessageQueryWrapper.eq("site_code", adwebSite.getCode());
                List<EnquiryEmailMessage> enquiryEmailMessages = enquiryEmailMessageService.list(enquiryEmailMessageQueryWrapper);
                List<EnquiryEmailMessage> sameEnquiryEmailMessageList = new ArrayList<>();
                if (CollectionUtils.isNotEmpty(enquiryEmailMessages)) {
                    for (EnquiryEmailMessage enquiryEmailMessage : enquiryEmailMessages) {
                        for (EnquiryEmailMessage enquiryEmailMessage1 : enquiryEmailMessageList) {
                            if (enquiryEmailMessage.getEnquiryId().equals(enquiryEmailMessage1.getEnquiryId()) && enquiryEmailMessage.getEmail().equals(enquiryEmailMessage1.getEmail())) {
                                sameEnquiryEmailMessageList.add(enquiryEmailMessage1);
                            }
                        }
                    }
                    enquiryEmailMessageList.removeAll(sameEnquiryEmailMessageList);
                }
                log.info("最终添加的询盘邮件：{}", FastJsonUtil.toJSONString(enquiryEmailMessageList));
                enquiryEmailMessageService.saveBatch(enquiryEmailMessageList);
                try {
                    for (EnquiryEmailMessage message : enquiryEmailMessageList) {
                        ObjectMapper objectMapper = new ObjectMapper();
                        JedisUtil.lpush(redisKey, objectMapper.writeValueAsBytes(message.getEnquiryId()));
                        JedisUtil.publishMsg(EnquiryConstants.ENQUIRY_EMAIL_CHANNEL, EnquiryConstants.ENQUIRY_EMAIL);
                    }
                } catch (Exception e) {
                    log.info("推送发送询盘邮件的消息失败", e);
                }
            }
        }
    }

    /**
     * 特殊账号发送邮件
     *
     * @param enquiryList
     * @param adwebSite
     */
    public void specialSendEmail(List<AdwebEnquiry> enquiryList, AdwebSite adwebSite) {
        //通过主账号id获取子账号id集合
        List<String> idList = masterSubAccountRelationService.getSubAccountIdByMaster(adwebSite.getUid());

        //获取子账号信息
        QueryWrapper<SysUser> sysUserQueryWrapper = new QueryWrapper<>();
        sysUserQueryWrapper.eq("is_inquiry", 2);
        sysUserQueryWrapper.eq("status", 1);
        if (CollectionUtils.isNotEmpty(idList)) {
            sysUserQueryWrapper.in("id", idList);
        }
        List<SysUser> sysUsers = sysUserService.list(sysUserQueryWrapper);


        for (AdwebEnquiry adwebEnquiry : enquiryList) {
            List<EnquiryEmailMessage> enquiryEmailMessageList = new ArrayList<>();
            if (adwebEnquiry.getWasteEnquiry() != 1 && adwebEnquiry.getStatus() != 0) {
                //当前发送邮件的账号
                SysUser sysUser = new SysUser();

                //如果没有子账号，则只给主账号发送邮件
                if (CollectionUtils.isEmpty(sysUsers)) {
                    //获取主账号
                    SysUser mainUser = sysUserService.getById(adwebSite.getUid());
                    //主账号邮件信息添加
                    if (mainUser != null && StringUtils.isNotBlank(mainUser.getEmail())) {
                        enquiryEmailMessageList.add(newEmail(adwebEnquiry, mainUser.getEmail()));
                    }
                }

                enquiryEmailMessageList.forEach(e -> System.out.println(e.getEmail()));

                log.info("需要添加的询盘邮件：{}", FastJsonUtil.toJSONString(enquiryEmailMessageList));
                if (CollectionUtils.isNotEmpty(enquiryEmailMessageList)) {
                    QueryWrapper<EnquiryEmailMessage> enquiryEmailMessageQueryWrapper = new QueryWrapper<>();
                    enquiryEmailMessageQueryWrapper.eq("site_code", adwebSite.getCode());
                    List<EnquiryEmailMessage> enquiryEmailMessages = enquiryEmailMessageService.list(enquiryEmailMessageQueryWrapper);
                    List<EnquiryEmailMessage> sameEnquiryEmailMessageList = new ArrayList<>();
                    if (CollectionUtils.isNotEmpty(enquiryEmailMessages)) {
                        for (EnquiryEmailMessage enquiryEmailMessage : enquiryEmailMessages) {
                            for (EnquiryEmailMessage enquiryEmailMessage1 : enquiryEmailMessageList) {
                                if (enquiryEmailMessage.getEnquiryId().equals(enquiryEmailMessage1.getEnquiryId()) && enquiryEmailMessage.getEmail().equals(enquiryEmailMessage1.getEmail())) {
                                    sameEnquiryEmailMessageList.add(enquiryEmailMessage1);
                                }
                            }
                        }
                        enquiryEmailMessageList.removeAll(sameEnquiryEmailMessageList);
                    }
                    log.info("最终添加的询盘邮件：{}", FastJsonUtil.toJSONString(enquiryEmailMessageList));
                    enquiryEmailMessageService.saveBatch(enquiryEmailMessageList);
                    try {
                        for (EnquiryEmailMessage message : enquiryEmailMessageList) {
                            ObjectMapper objectMapper = new ObjectMapper();
                            JedisUtil.lpush(redisKey, objectMapper.writeValueAsBytes(message.getEnquiryId()));
                            JedisUtil.publishMsg(EnquiryConstants.ENQUIRY_EMAIL_CHANNEL, EnquiryConstants.ENQUIRY_EMAIL);
                        }
                        SysUser user = sysUserService.getById(adwebEnquiry.getPrincipalUid());
                        if (StringUtils.isNotBlank(adwebEnquiry.getRecordId())) {
                            returnSalesperson(adwebSite.getCode(), adwebEnquiry.getRecordId(), user.getUsername());
                        }
                    } catch (Exception e) {
                        log.info("推送发送询盘邮件的消息失败", e);
                    }
                }

            }
        }
    }


    /**
     * 根据询盘信息创建邮件发送记录
     *
     * @param adwebEnquiry 询盘信息
     * @param email        接收邮箱
     * @return
     */
    private static EnquiryEmailMessage newEmail(AdwebEnquiry adwebEnquiry, String email) {
        EnquiryEmailMessage enquiryEmailMessage = new EnquiryEmailMessage();
        enquiryEmailMessage.setEnquiryId(adwebEnquiry.getId());
        enquiryEmailMessage.setEmail(email);
        enquiryEmailMessage.setFromEmail(adwebEnquiry.getFromEmail());
        enquiryEmailMessage.setCreateTime(new Date());
        enquiryEmailMessage.setSiteCode(adwebEnquiry.getSiteCode());
        enquiryEmailMessage.setSendStatus(EnquirySendStatus.WAIT_SEND);
        enquiryEmailMessage.setSendErrorNum(0);

        return enquiryEmailMessage;
    }


    /**
     * 通过询盘中的ip字段，获取国家信息并放在询盘对象种
     *
     * @param enquiry 询盘对象
     */
    private void setCountryByIp(AdwebEnquiry enquiry) {
        CountryAreaApiDto countryAreaApiDto = geoIpUtil.getCountryAndAreaByIp(enquiry.getFromIp());
        if (countryAreaApiDto != null) {
            String countryCode = countryAreaApiDto.getCountryIsoCode();
            if ("TW".equals(countryCode)) {
                countryCode = "CN";
            }
            String countryName = countryAreaApiDto.getCountryZhCN();
            if ("中华民国".equals(countryName)) {
                countryName = "中国";
            }
            enquiry.setCountryCode(countryCode);
            enquiry.setCountryName(countryName);
            if (StringUtils.isBlank(enquiry.getCountry())) {
                enquiry.setCountry(countryName);
            }
        } else {
            enquiry.setCountryCode("0000");
            enquiry.setCountryName("其它");
        }
    }

    /**
     * 根据询盘对象和站点，构建一个本系统中的询盘对象
     *
     * @param enquiryDto 询盘对象
     * @param adwebSite  询盘所属站点
     * @return 本系统中的询盘队形
     */
    private AdwebEnquiry createEnquiry(EnquiryDTO enquiryDto, AdwebSite adwebSite) {
        AdwebEnquiry adwebEnquiry = new AdwebEnquiry();
        adwebEnquiry.setId(snowflakeIdUtil.nextId());
        adwebEnquiry.setCtime(new Date());
        adwebEnquiry.setStatus(1);
        adwebEnquiry.setVisitId(enquiryDto.getVisitId());
        adwebEnquiry.setSiteId(adwebSite.getId());
        adwebEnquiry.setUid(adwebSite.getUid());
        adwebEnquiry.setFromIp(enquiryDto.getFromIp());
        adwebEnquiry.setFromEmail(enquiryDto.getFromEmail());
        adwebEnquiry.setPluginName(enquiryDto.getPluginName());
        adwebEnquiry.setRecordId(enquiryDto.getRecordId());
        adwebEnquiry.setModifyRecordCtime(geoIpUtil.getLocalhostTime(enquiryDto.getFromIp(), enquiryDto.getRecordCtime()));
        adwebEnquiry.setRecordCtime(enquiryDto.getRecordCtime());
        adwebEnquiry.setSiteCode(adwebSite.getCode());
        adwebEnquiry.setModular(enquiryDto.getPluginName());
        adwebEnquiry.setSysEffective(NumConstant.ONE);
        adwebEnquiry.setUserEffective(NumConstant.TWO);
        adwebEnquiry.setSiteHost(enquiryDto.getSiteHost());
        adwebEnquiry.setNo("xp" + DateUtil.formatDate(new Date(), DateUtil.DATE_FORMAT) + adwebOpenApiService.loadNo(adwebSite.getCode()));

        // 外部编号暂无作用，且多查询一次数据库，暂时注释
//        adwebEnquiry.setNoOut(DateUtil.dateToString(new Date(), DateUtil.DATE_FORMAT_THREE) + adwebOpenApiService.loadOutNoByUser(adwebSite.getUid()));
        adwebEnquiry.setWasteEnquiry(0);
        adwebEnquiry.setRequestTime(new Date());
        adwebEnquiry.setAcquireMessageTime(adwebSite.getEnquiryMessageTime());
        adwebEnquiry.setIsEnquirySync("enquirySync");

        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String jsonString = objectMapper.writeValueAsString(enquiryDto.getCartItems());
            adwebEnquiry.setCartItems(jsonString);
        } catch (JsonProcessingException e) {
            // 记录异常信息
            System.err.println("Error serializing cart items to JSON: " + e.getMessage());
            // 可以选择记录更详细的堆栈跟踪信息
            log.error(e.getMessage(), e);
        }
        return adwebEnquiry;
    }

    /**
     * 解析form，将form中的字段加入到询盘对象种
     *
     * @param enquiry 询盘对象
     * @param form    询盘表单信息
     */
    private void parseFormAndSetFields(AdwebEnquiry enquiry, String form, AdwebSite adwebSite) {
        long startTime = System.currentTimeMillis();

        List<String> nameKeys = this.getFormKeys("wp-name");
        List<String> emailKeys = this.getFormKeys("wp-email");
        List<String> messageKeys = this.getFormKeys("wp-content");
        List<String> companyKeys = this.getFormKeys("wp-company");
        List<String> fromPageKeys = this.getFormKeys("wp-page");
        List<String> phoneKeys = this.getFormKeys("wp-phone");
        List<String> whatsAppKeys = this.getFormKeys("wp-whatsapp");
        List<String> countryKeys = this.getFormKeys("wp-country");
        List<String> customerIpKeys = this.getFormKeys("wp-customerip");
        List<String> addressKeys = this.getFormKeys("wp-address");

        List<String> errorObjNames = new ArrayList<>();
        Collection<JSONObject> formItems = null;
        Map<String, JSONObject> formObj = FastJsonUtil.parseObject(form, Map.class);
        if (formObj == null || formObj.size() == 0) {
            List<JSONObject> formList = FastJsonUtil.parseObject(form, List.class);
            if (CollectionUtils.isNotEmpty(formList)) {
                formItems = formList;
            }
        } else {
            formItems = formObj.values();
        }

        List<EnquirySpecialFields> specialFieldsList = new ArrayList<>();
        for (JSONObject formItem : formItems) {
            String formItemName = formItem.getString("name");
            String formItemValue = formItem.getString("value");

            if (contains(nameKeys, formItemName)) {
                enquiry.setName(formItemValue);
            } else if (contains(emailKeys, formItemName)) {
                enquiry.setEmail(formItemValue);
            } else if (contains(messageKeys, formItemName)) {
                enquiry.setMessage(formItemValue);
            } else if (contains(companyKeys, formItemName)) {
                enquiry.setCompany(formItemValue);
            } else if (contains(fromPageKeys, formItemName)) {
                enquiry.setFromPage(formItemValue);
            } else if (contains(phoneKeys, formItemName)) {
                enquiry.setPhone(formItemValue);
            } else if (contains(whatsAppKeys, formItemName)) {
                enquiry.setWhatsApp(formItemValue);
            } else if (contains(countryKeys, formItemName)) {
                enquiry.setCountry(formItemValue);
            } else if (contains(customerIpKeys, formItemName)) {
                enquiry.setCustomerIp(formItemValue);
            } else if (contains(addressKeys, formItemName)) {
                enquiry.setAddress(formItemValue);
            } else {
                // 异常字段
                errorObjNames.add(formItemName);
                EnquirySpecialFields enquirySpecialFields = new EnquirySpecialFields();
                enquirySpecialFields.setField(formItemName);
                enquirySpecialFields.setValue(formItemValue);
                specialFieldsList.add(enquirySpecialFields);
            }
        }

        String specialField = FastJsonUtil.toJSONString(specialFieldsList);
        enquiry.setSpecialField(specialField);

        if (errorObjNames.size() > 0 || enquiry.getRecordCtime() == null || StringUtil.isEmpty(enquiry.getMessage()) || StringUtil.isEmpty(enquiry.getEmail()) || StringUtil.isEmpty(enquiry.getFromPage())) {
            //发送飞书告警
            StringBuilder msg = new StringBuilder("询盘异常,\n询盘id：" + enquiry.getId() + ",\n站点名称：" + adwebSite.getName() + ",\n站点域名：" + enquiry.getSiteHost() + ",\n来源ip：" + enquiry.getFromIp());
            if (errorObjNames.size() > 0) {
                msg.append(",\n字段异常,存在异常字段：");
                for (String errorObjName : errorObjNames) {
                    msg.append(errorObjName).append("、");
                }
                msg.deleteCharAt(msg.length() - 1);
            }
            if (enquiry.getRecordCtime() == null) {
                msg.append(",\n询盘发送时间为空");
            }
            if (StringUtil.isEmpty(enquiry.getMessage())) {
                msg.append(",\n询盘内容为空");
            }
            if (StringUtil.isEmpty(enquiry.getEmail())) {
                msg.append(",\n邮箱内容为空");
            }
            if (StringUtil.isEmpty(enquiry.getFromPage())) {
                msg.append(",\n来源页面为空");
            }
            // 同一个站点，一天最多报错一次
            String flag = adwebRedisUtil.getString("forbidden_send_error_msg_by_enquiry_field_" + adwebSite.getDomain());
            if (StringUtils.isNotBlank(flag)) {
                log.info("同一个站点，一天最多报错一次，站点域名：" + adwebSite.getDomain());
                return;
            }
            adwebRedisUtil.set("forbidden_send_error_msg_by_enquiry_field_" + adwebSite.getDomain(), "forbidden", 60 * 60 * 24);

            // 异常入库
            SysException exception = new SysException();
            exception.setType(0);
            exception.setFunctionModule("询盘字段配置异常");
            exception.setExceptionDetail(msg.toString());
            exception.setCreateTime(new Date());
            exception.setStatus(1);
            exception.setHandle(0);
            exception.setPriority(1);
            sysExceptionService.save(exception);

            long diffTime = System.currentTimeMillis() - startTime;
            String className = this.getClass().getName();
            String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
            feishuService.sendRobot((float) diffTime / 1000, "wpforms-询盘警告：" + 0,
                    className, methodName, String.valueOf(msg));
        }
    }

    private boolean contains(List<String> keys, String key) {
        if (CollectionUtils.isEmpty(keys) || StringUtil.isEmpty(key)) {
            return false;
        }
        key = key.replace(":", "").replace("：", "").replaceAll(" {2,}", " ").toLowerCase().trim();
        return keys.contains(key);
    }

    /**
     * 根据字典code，获取相应数据在json中所有可能的key，用来解析json
     *
     * @param dictCode 字典code
     * @return key的集合
     */
    private List<String> getFormKeys(String dictCode) {
        String formKey = CacheConstant.SYS_DICT_CACHE + "::" + dictCode;
        Object obj = adwebRedisUtil.get(formKey);
        if (obj != null) {
            List<String> keys = (List<String>) obj;
            return keys;
        }
        List<SysDictItem> dictItems = sysAdwebApiImpl.selectItemsByDictCode(dictCode);
        List<String> keys = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(dictItems)) {
            for (SysDictItem item : dictItems) {
                String value = item.getItemValue();
                if (StringUtil.isEmpty(value)) {
                    continue;
                }
                value = value.replaceAll(" {2,}", " ").toLowerCase().trim();
                if (!keys.contains(value)) {
                    keys.add(value);
                }
            }
        }
        adwebRedisUtil.set(formKey, keys, 60 * 60);
        return keys;
    }

    /**
     * 判断邮件是否是垃圾询盘
     * 1、邮件过滤
     * 2、根据邮件是否包含外部url过滤
     * 3、根据关键词过滤
     *
     * @param adwebEnquiryList 询盘列表
     */
    private void judgeWasteEnquiryBySiteId(List<AdwebEnquiry> adwebEnquiryList, AdwebSite adwebSite, List<String> blackWordList) {

        //邮箱 黑名单
        //先获取对应站点的邮箱黑名单
        List<String> siteBlackEmailList = (List<String>) adwebRedisUtil.get(SiteBlackEmailKey + "::" + adwebSite.getId());
        if (CollectionUtils.isEmpty(siteBlackEmailList)) {
            enquirySiteBlackEmailService.saveRedisSiteBlackEmailBySiteId(adwebSite.getId(), 0);
            siteBlackEmailList = (List<String>) adwebRedisUtil.get(SiteBlackEmailKey + "::" + adwebSite.getId());
            if (CollectionUtils.isEmpty(siteBlackEmailList)) {
                siteBlackEmailList = new ArrayList<>();
            }
        }

        //邮箱 公共黑名单
        List<String> publicBlackEmailList = (List<String>) adwebRedisUtil.get(BlackEmailKey);
        if (CollectionUtils.isEmpty(publicBlackEmailList)) {
            List<AdwebPublicBlackEmail> enquiryPublicBlackEmailList = adwebPublicBlackEmailService
                    .list(new LambdaQueryWrapper<AdwebPublicBlackEmail>()
                            .ne(AdwebPublicBlackEmail::getStatus, 0)
                            .eq(AdwebPublicBlackEmail::getBlackOrWhite, 0)
                            .isNotNull(AdwebPublicBlackEmail::getEmail)
                            .select(AdwebPublicBlackEmail::getEmail));

            if (CollectionUtils.isNotEmpty(enquiryPublicBlackEmailList)) {
                publicBlackEmailList = enquiryPublicBlackEmailList.stream().map(AdwebPublicBlackEmail::getEmail).filter(StringUtil::isNotEmpty).collect(Collectors.toList());
                adwebRedisUtil.set(BlackEmailKey, publicBlackEmailList, 60 * 60 * 24);
            } else {
                publicBlackEmailList = new ArrayList<>();
            }
        } else {
            publicBlackEmailList = publicBlackEmailList.stream().filter(s -> !s.isEmpty()).collect(Collectors.toList());
        }
        List<String> allBlackEmailList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(siteBlackEmailList)) {
            allBlackEmailList = new ArrayList<>(siteBlackEmailList);
        }
        allBlackEmailList.addAll(publicBlackEmailList);
        List<String> blackEmailList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(allBlackEmailList)) {
            HashSet<String> blackEmailHashSet = new HashSet<String>(allBlackEmailList);
            blackEmailList = new ArrayList<>(blackEmailHashSet);
        }
        log.info("公共邮箱黑名单：" + publicBlackEmailList.size());
        log.info("站点邮箱黑名单：" + siteBlackEmailList.size());

        //邮箱 白名单
        //先获取对应站点的邮箱白名单
        List<String> siteWhiteEmailList = (List<String>) adwebRedisUtil.get(SiteWhiteEmailListKey + "::" + adwebSite.getId());
        if (CollectionUtils.isEmpty(siteWhiteEmailList)) {
            enquirySiteBlackEmailService.saveRedisSiteBlackEmailBySiteId(adwebSite.getId(), 1);
            siteWhiteEmailList = (List<String>) adwebRedisUtil.get(SiteWhiteEmailListKey + "::" + adwebSite.getId());
        }
        //公共邮箱白名单数据
        List<String> publicWhiteEmailList = (List<String>) adwebRedisUtil.get(WhiteEmailListKey);
        if (CollectionUtils.isEmpty(publicWhiteEmailList)) {
            List<AdwebPublicBlackEmail> enquiryPublicWhiteEmailList = adwebPublicBlackEmailService
                    .list(new LambdaQueryWrapper<AdwebPublicBlackEmail>()
                            .ne(AdwebPublicBlackEmail::getStatus, 0)
                            .eq(AdwebPublicBlackEmail::getBlackOrWhite, 1)
                            .isNotNull(AdwebPublicBlackEmail::getEmail)
                            .select(AdwebPublicBlackEmail::getEmail));

            if (CollectionUtils.isNotEmpty(enquiryPublicWhiteEmailList)) {
                publicWhiteEmailList = enquiryPublicWhiteEmailList.stream().map(AdwebPublicBlackEmail::getEmail).filter(StringUtil::isNotEmpty).collect(Collectors.toList());
                adwebRedisUtil.set(WhiteEmailListKey, publicWhiteEmailList, 60 * 60 * 24);
            } else {
                publicWhiteEmailList = new ArrayList<>();
            }
        } else {
            publicWhiteEmailList = publicWhiteEmailList.stream().filter(s -> !s.isEmpty()).collect(Collectors.toList());
        }
        List<String> allWhiteEmailList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(siteWhiteEmailList)) {
            allWhiteEmailList = new ArrayList<>(siteWhiteEmailList);
        }
        allWhiteEmailList.addAll(publicWhiteEmailList);
        List<String> whiteEmailList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(allWhiteEmailList)) {
            HashSet<String> whiteEmailHashSet = new HashSet<String>(allWhiteEmailList);
            whiteEmailList = new ArrayList<>(whiteEmailHashSet);
        }

        log.info("公共邮箱白名单：" + FastJsonUtil.toJSONString(publicWhiteEmailList));
        log.info("站点邮箱白名单：" + FastJsonUtil.toJSONString(siteWhiteEmailList));

        //Ip黑名单
        //公共ip黑名单
        List<String> publicBlackIpList = (List<String>) adwebRedisUtil.get(BlackIpKey);
        if (CollectionUtils.isEmpty(publicBlackIpList)) {
            List<AdwebPublicBlackIp> enquiryPublicBlackIpList = adwebPublicBlackIpService
                    .list(new LambdaQueryWrapper<AdwebPublicBlackIp>()
                            .ne(AdwebPublicBlackIp::getStatus, 0)
                            .eq(AdwebPublicBlackIp::getBlackOrWhite, 0)
                            .select(AdwebPublicBlackIp::getIp));
            if (CollectionUtils.isNotEmpty(enquiryPublicBlackIpList)) {
                publicBlackIpList = enquiryPublicBlackIpList.stream().map(AdwebPublicBlackIp::getIp).collect(Collectors.toList());
                adwebRedisUtil.set(BlackIpKey, publicBlackIpList, 60 * 60 * 24);
            } else {
                publicBlackIpList = new ArrayList<>();
            }
        }
        //站点ip黑名单
        List<String> siteBlackIpList = (List<String>) adwebRedisUtil.get(SiteBlackIpKey + "::" + adwebSite.getId());
        if (CollectionUtils.isEmpty(siteBlackIpList)) {
            List<AdwebSiteBlackIp> enquirySiteBlackIpList = adwebSiteBlackIpService
                    .list(new LambdaQueryWrapper<AdwebSiteBlackIp>()
                            .ne(AdwebSiteBlackIp::getStatus, 0)
                            .eq(AdwebSiteBlackIp::getBlackOrWhite, 0)
                            .eq(AdwebSiteBlackIp::getSiteId, adwebSite.getId())
                            .select(AdwebSiteBlackIp::getIp));
            if (CollectionUtils.isNotEmpty(enquirySiteBlackIpList)) {
                siteBlackIpList = enquirySiteBlackIpList.stream().map(AdwebSiteBlackIp::getIp).collect(Collectors.toList());
                adwebRedisUtil.set(SiteBlackIpKey + "::" + adwebSite.getId(), siteBlackIpList, 60 * 60 * 24);
            } else {
                siteBlackIpList = new ArrayList<>();
            }
        }
        List<String> allBlackIpList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(siteBlackIpList)) {
            allBlackIpList = new ArrayList<>(siteBlackIpList);
        }
        allBlackIpList.addAll(publicBlackIpList);
        List<String> blackIpList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(allBlackIpList)) {
            HashSet<String> blackIpHashSet = new HashSet<String>(allBlackIpList);
            blackIpList = new ArrayList<>(blackIpHashSet);
        }

        log.info("公共ip黑名单：{} 个", publicBlackIpList.size());
        log.info("站点ip黑名单：{} 个", siteBlackIpList.size());

        //Ip白名单
        //公共Ip白名单
        List<String> publicWhiteIpList = (List<String>) adwebRedisUtil.get(WhiteIpListKey);
        if (publicWhiteIpList == null) {
            List<AdwebPublicBlackIp> enquiryPublicWhiteIpList = adwebPublicBlackIpService
                    .list(new LambdaQueryWrapper<AdwebPublicBlackIp>()
                            .ne(AdwebPublicBlackIp::getStatus, 0)
                            .eq(AdwebPublicBlackIp::getBlackOrWhite, 1)
                            .select(AdwebPublicBlackIp::getIp));
            if (CollectionUtils.isNotEmpty(enquiryPublicWhiteIpList)) {
                publicWhiteIpList = enquiryPublicWhiteIpList.stream().map(AdwebPublicBlackIp::getIp).collect(Collectors.toList());
                adwebRedisUtil.set(WhiteIpListKey, publicWhiteIpList, 60 * 60 * 24);
            } else {
                publicWhiteIpList = new ArrayList<>();
            }
        }
        //站点Ip白名单, 基于站点查询
        List<String> siteWhiteIpList = (List<String>) adwebRedisUtil.get(SiteWhiteIpListKey + "::" + adwebSite.getId());
        if (CollectionUtils.isEmpty(siteWhiteIpList)) {
            List<AdwebSiteBlackIp> enquirySiteWhiteIpList = adwebSiteBlackIpService
                    .list(new LambdaQueryWrapper<AdwebSiteBlackIp>()
                            .ne(AdwebSiteBlackIp::getStatus, 0)
                            .eq(AdwebSiteBlackIp::getBlackOrWhite, 1)
                            .eq(AdwebSiteBlackIp::getSiteId, adwebSite.getId())
                            .select(AdwebSiteBlackIp::getIp));
            if (CollectionUtils.isNotEmpty(enquirySiteWhiteIpList)) {
                siteWhiteIpList = enquirySiteWhiteIpList.stream().map(AdwebSiteBlackIp::getIp).collect(Collectors.toList());
                adwebRedisUtil.set(SiteWhiteIpListKey + "::" + adwebSite.getId(), siteWhiteIpList, 60 * 60 * 24);
            } else {
                siteWhiteIpList = new ArrayList<>();
            }
        }
        List<String> allWhiteIpList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(siteWhiteIpList)) {
            allWhiteIpList = new ArrayList<>(siteWhiteIpList);
        }
        allWhiteIpList.addAll(publicWhiteIpList);
        List<String> whiteIpList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(allWhiteIpList)) {
            HashSet<String> whiteIpHashSet = new HashSet<String>(allWhiteIpList);
            whiteIpList = new ArrayList<>(whiteIpHashSet);
        }

        log.info("公共ip白名单：" + FastJsonUtil.toJSONString(publicWhiteIpList));
        log.info("站点ip白名单：" + FastJsonUtil.toJSONString(siteWhiteIpList));

        //站点询盘规则黑名单
        QueryWrapper<AdwebSiteEnquiryRule> adwebEnquirySiteRuleQueryWrapper = new QueryWrapper<>();
        adwebEnquirySiteRuleQueryWrapper.eq("site_id", adwebSite.getId());
        adwebEnquirySiteRuleQueryWrapper.eq("status", 1);
        adwebEnquirySiteRuleQueryWrapper.eq("black_or_white", 0);
        List<AdwebSiteEnquiryRule> siteBlackRuleList = adwebSiteEnquiryRuleService.list(adwebEnquirySiteRuleQueryWrapper);
        log.info("站点关键词黑名单：" + FastJsonUtil.toJSONString(siteBlackRuleList));

        //判断上一封询盘是否是垃圾询盘
        AdwebEnquiry isJudgeWasteEnquiry = new AdwebEnquiry();

        // 判断是否垃圾询盘
        outerloop:
        for (AdwebEnquiry adwebEnquiry : adwebEnquiryList) {
            // 没有message的无法判断，认为是普通询盘
            if (StringUtil.isEmpty(adwebEnquiry.getMessage())) {
                adwebEnquiry.setWasteEnquiry(1);
                adwebEnquiry.setUserEffective(0);
                log.info("询盘id是:{}, 站点code是:{}, 通过——询盘内容为空——检测到垃圾询盘",
                        adwebEnquiry.getId(), adwebEnquiry.getSiteCode());
                continue;
            }

            //该分支用于判断上一封邮件是否为垃圾询盘
            dealMultipleRepeatInfoEnquiry(siteBlackEmailList, siteBlackIpList, isJudgeWasteEnquiry, adwebSite);
            isJudgeWasteEnquiry = adwebEnquiry;

            // 判断 询盘邮箱黑名单
            if (CollectionUtils.isNotEmpty(blackEmailList) || StringUtils.isNotBlank(adwebEnquiry.getEmail())) {

                String email = adwebEnquiry.getEmail().toLowerCase();

                String message = adwebEnquiry.getMessage().replaceAll("[\\n\\t]", " ").replaceAll(" {2,}", " ").toLowerCase();


                //公共黑白名单
//                boolean isContainPublicWhite = false;
//                String containPublicWhiteStr = "";
                //白名单
//                for(String publicWhiteEmail : publicWhiteEmailList){
//                    log.info("judgeWasteEnquiry -- 当前询盘Id:{}，!whiteEmailList.contains(email):{}",adwebEnquiry.getId(),!whiteEmailList.contains(email));
//                    if(email.equals(publicWhiteEmail) || message.equals(publicWhiteEmail)){
//                        containPublicWhiteStr = publicWhiteEmail;
//                        isContainPublicWhite = true;
//                        break;
//                    }
//                }

                //黑名单
                String containPublicBlackStr = "";
                boolean isContainPublicBlack = false;
                if (CollectionUtils.isNotEmpty(publicBlackEmailList)) {
                    for (String blackEmail : publicBlackEmailList) {
                        String allBlackEmail = blackEmail;
                        if (allBlackEmail.contains("*")) {
                            allBlackEmail = allBlackEmail.substring(1, allBlackEmail.length() - 1);
                            if (email.contains(allBlackEmail) || message.contains(allBlackEmail)) {
                                containPublicBlackStr = blackEmail;
                                isContainPublicBlack = true;
                                break;
                            }
                        } else {
                            if (email.equals(allBlackEmail) || message.equals(allBlackEmail)) {
                                containPublicBlackStr = blackEmail;
                                isContainPublicBlack = true;
                                break;
                            }
                        }
                    }
                }
                log.info("是否是公共黑名单：" + isContainPublicBlack);
                log.info("匹配的公共黑名单：" + containPublicBlackStr);
                //站点黑白名单
                boolean isContainSiteWhite = false;
                boolean isSiteAllContain = true;
                String containSiteWhiteStr = "";
                //白名单
                if (CollectionUtils.isNotEmpty(siteWhiteEmailList)) {
                    for (String whiteEmail : siteWhiteEmailList) {
                        String compareWhiteEmail = whiteEmail;
                        if (compareWhiteEmail.contains("*")) {
                            compareWhiteEmail = whiteEmail.substring(1, whiteEmail.length() - 1);
                            if (email.contains(compareWhiteEmail) || message.contains(compareWhiteEmail)) {
                                containSiteWhiteStr = compareWhiteEmail;
                                isContainSiteWhite = true;
                                isSiteAllContain = false;
                                break;
                            }
                        } else {
                            if (email.equals(compareWhiteEmail) || message.equals(compareWhiteEmail)) {
                                containSiteWhiteStr = compareWhiteEmail;
                                isContainSiteWhite = true;
                                isSiteAllContain = false;
                                break;
                            }
                        }
                    }
                }


                log.info("是否是站点白名单：" + isContainSiteWhite);
                log.info("匹配的站点白名单：" + containSiteWhiteStr);
                //黑名单
                boolean isContainSiteBlack = false;
                String containSiteBlackStr = "";
                if (CollectionUtils.isNotEmpty(siteBlackEmailList)) {
                    for (String blackEmail : siteBlackEmailList) {
                        String allBlackEmail = blackEmail;
                        if (allBlackEmail.contains("*")) {
                            allBlackEmail = allBlackEmail.substring(1, allBlackEmail.length() - 1);
                            if (email.contains(allBlackEmail) || message.contains(allBlackEmail)) {
                                containSiteBlackStr = allBlackEmail;
                                isContainSiteBlack = true;
                                isSiteAllContain = false;
                                break;
                            }
                        } else {
                            if (email.equals(allBlackEmail) || message.equals(allBlackEmail)) {
                                containSiteBlackStr = allBlackEmail;
                                isContainSiteBlack = true;
                                isSiteAllContain = false;
                                break;
                            }
                        }
                    }
                }


                log.info("是否是站点黑名单：" + isContainSiteBlack);
                log.info("匹配的站点黑名单：" + containSiteBlackStr);
                //判断邮箱或者内容即在黑名单里又在白名单里，特殊处理
                if (isContainSiteBlack && isContainSiteWhite) {
                    if (containSiteBlackStr.length() <= containSiteWhiteStr.length()) {
                        isContainSiteBlack = false;
                    }
                }

                log.info("第二次处理是否是站点黑名单：" + isContainSiteBlack);
                if (isContainPublicBlack || !isSiteAllContain) {
                    if (isContainPublicBlack && isContainSiteBlack) {
                        adwebEnquiry.setWasteEnquiry(1);
                        adwebEnquiry.setUserEffective(0);
                        adwebEnquiry.setWasteEnquiryType("email");
                        adwebEnquiry.setEffectiveReason("系统操作-通过公共和站点的询盘邮箱黑名单检测到垃圾询盘-" + containSiteBlackStr);
                        log.info("询盘id是:{}, 站点code是:{}, 通过——询盘邮箱黑名单——检测到垃圾询盘, 黑名单邮箱是:{}",
                                adwebEnquiry.getId(), adwebEnquiry.getSiteCode(), containSiteBlackStr);
                        continue outerloop;
                    }
                    if (isContainPublicBlack && isSiteAllContain) {
                        adwebEnquiry.setWasteEnquiry(1);
                        adwebEnquiry.setUserEffective(0);
                        adwebEnquiry.setWasteEnquiryType("email");
                        adwebEnquiry.setEffectiveReason("系统操作-通过公共的询盘邮箱黑名单检测到垃圾询盘-" + containPublicBlackStr);
                        log.info("询盘id是:{}, 站点code是:{}, 通过——询盘邮箱黑名单——检测到垃圾询盘, 黑名单邮箱是:{}",
                                adwebEnquiry.getId(), adwebEnquiry.getSiteCode(), containPublicBlackStr);
                        continue outerloop;
                    }
                    if (!isContainPublicBlack && isContainSiteBlack) {
                        adwebEnquiry.setWasteEnquiry(1);
                        adwebEnquiry.setUserEffective(0);
                        adwebEnquiry.setWasteEnquiryType("email");
                        adwebEnquiry.setEffectiveReason("系统操作-通过站点的询盘邮箱黑名单检测到垃圾询盘-" + containSiteBlackStr);
                        log.info("询盘id是:{}, 站点code是:{}, 通过——询盘邮箱黑名单——检测到垃圾询盘, 黑名单邮箱是:{}",
                                adwebEnquiry.getId(), adwebEnquiry.getSiteCode(), containSiteBlackStr);
                        continue outerloop;
                    }
                }
            }

            // @see http://52.83.154.198:8082/browse/ADWEBV2-12
            // 垃圾询盘过滤时IP按照客户IP去使用黑名单过滤而不再使用来源IP
            // 判断是否为ip黑名单
            if (CollectionUtils.isNotEmpty(blackIpList) || StringUtils.isNotBlank(adwebEnquiry.getCustomerIp())) {
                String ip = adwebEnquiry.getCustomerIp();
                //公共ip黑名单
                boolean isPublicIp = false;
                if (publicBlackIpList.contains(ip) && !publicWhiteIpList.contains(ip)) {
                    isPublicIp = true;
                }

                //站点ip黑名单
                boolean isSiteIp = false;
                if (siteBlackIpList.contains(ip) && !siteWhiteIpList.contains(ip)) {
                    isSiteIp = true;
                }
                if (isPublicIp || isSiteIp) {
                    adwebEnquiry.setWasteEnquiry(1);
                    adwebEnquiry.setUserEffective(0);
                    adwebEnquiry.setWasteEnquiryType("ip");
                }
                if (isPublicIp && isSiteIp) {
                    adwebEnquiry.setEffectiveReason("系统操作-通过询盘公共和站点ip黑名单检测到垃圾询盘-" + ip);
                    log.info("询盘id是:{}, 站点code是:{}, 通过——询盘公共和站点ip黑名单——检测到垃圾询盘, ip是:{}",
                            adwebEnquiry.getId(), adwebEnquiry.getSiteCode(), ip);
                    continue;
                }
                if (isPublicIp) {
                    adwebEnquiry.setEffectiveReason("系统操作-通过询盘公共ip黑名单检测到垃圾询盘-" + ip);
                    log.info("询盘id是:{}, 站点code是:{}, 通过——询盘公共ip黑名单——检测到垃圾询盘, ip是:{}",
                            adwebEnquiry.getId(), adwebEnquiry.getSiteCode(), ip);
                    continue;
                }
                if (isSiteIp) {
                    adwebEnquiry.setEffectiveReason("系统操作-通过询盘站点ip黑名单检测到垃圾询盘-" + ip);
                    log.info("询盘id是:{}, 站点code是:{}, 通过——询盘站点ip黑名单——检测到垃圾询盘, ip是:{}",
                            adwebEnquiry.getId(), adwebEnquiry.getSiteCode(), ip);
                    continue;
                }

            }

            // 判断邮箱是否包含外部链接
            List<String> urlList = parser(adwebEnquiry.getMessage());
            if (StringUtils.isNotBlank(adwebSite.getDomain())) {
                for (String url : urlList) {
                    if (!adwebSite.getDomain().contains(url)) {
                        adwebEnquiry.setWasteEnquiry(1);
                        adwebEnquiry.setUserEffective(0);
                        adwebEnquiry.setWasteEnquiryType("other");
                        adwebEnquiry.setEffectiveReason("系统操作-通过站点url检测到垃圾询盘-" + url);
                        log.info("询盘id是:{}, 站点code是:{}, 通过——站点url——检测到垃圾询盘",
                                adwebEnquiry.getId(), adwebEnquiry.getSiteCode());
                        continue outerloop;
                    }
                }
            } else {
                if (CollectionUtils.isNotEmpty(urlList)) {
                    adwebEnquiry.setWasteEnquiry(1);
                    adwebEnquiry.setUserEffective(0);
                    adwebEnquiry.setWasteEnquiryType("other");
                    adwebEnquiry.setEffectiveReason("系统操作-通过站点url检测到垃圾询盘-空");
                    log.info("询盘id是:{}, 站点code是:{}, 通过——站点url——检测到垃圾询盘",
                            adwebEnquiry.getId(), adwebEnquiry.getSiteCode());
                    continue;
                }
            }

            // 判断询盘是否包含关键词
            String message = adwebEnquiry.getMessage().replaceAll("[\\n\\t]",
                    " ").replaceAll(" {2,}", " ").toLowerCase();
            if (CollectionUtils.isNotEmpty(blackWordList) || CollectionUtils.isNotEmpty(siteBlackRuleList)) {
                //公共关键词黑名单
                boolean isPublicWord = false;
                String isBlackWord = "";
                for (String blackWord : blackWordList) {
                    if (message.contains(blackWord)) {
                        isPublicWord = true;
                        isBlackWord = blackWord;
                    }
                }
                //站点关键词黑名单
                boolean isSiteWord = false;
                for (AdwebSiteEnquiryRule siteBlackRule : siteBlackRuleList) {
                    if (message.contains(siteBlackRule.getWord())) {
                        isSiteWord = true;
                        isBlackWord = siteBlackRule.getWord();
                    }
                }
                if (isPublicWord || isSiteWord) {
                    adwebEnquiry.setWasteEnquiry(1);
                    adwebEnquiry.setUserEffective(0);
                    adwebEnquiry.setWasteEnquiryType("keyword");
                }
                if (isPublicWord && isSiteWord) {
                    adwebEnquiry.setEffectiveReason("系统操作-通过公共和站点关键词黑名单检测到垃圾询盘-" + isBlackWord);
                    log.info("询盘id是:{}, 站点code是:{}, 通过——公共和站点关键词黑名单——检测到垃圾询盘, 关键词是:{}",
                            adwebEnquiry.getId(), adwebEnquiry.getSiteCode(), isBlackWord);
                    continue outerloop;
                }
                if (isPublicWord) {
                    adwebEnquiry.setEffectiveReason("系统操作-通过公共关键词黑名单检测到垃圾询盘-" + isBlackWord);
                    log.info("询盘id是:{}, 站点code是:{}, 通过——公共关键词黑名单——检测到垃圾询盘, 关键词是:{}",
                            adwebEnquiry.getId(), adwebEnquiry.getSiteCode(), isBlackWord);
                    continue outerloop;
                }
                if (isSiteWord) {
                    adwebEnquiry.setEffectiveReason("系统操作-通过站点关键词黑名单检测到垃圾询盘-" + isBlackWord);
                    log.info("询盘id是:{}, 站点code是:{}, 通过——站点关键词黑名单——检测到垃圾询盘, 关键词是:{}",
                            adwebEnquiry.getId(), adwebEnquiry.getSiteCode(), isBlackWord);
                    continue outerloop;
                }
            }

            // 分词判断
            if (validateWordLength(adwebEnquiry.getMessage())) {
                adwebEnquiry.setWasteEnquiry(1);
                adwebEnquiry.setUserEffective(0);
                adwebEnquiry.setWasteEnquiryType("other");
                adwebEnquiry.setEffectiveReason("系统操作-通过单词长度超过50个字符检测到垃圾询盘");
                log.info("询盘id是:{}, 站点code是:{}, 通过——单词长度超过50个字符——检测到垃圾询盘",
                        adwebEnquiry.getId(), adwebEnquiry.getSiteCode());
                continue;
            }

            boolean isBlackFlag = false;

            // 询盘为正常询盘
            // 判断十分钟和一天内同个站点是否有相同的邮箱
            if (StringUtils.isNotBlank(adwebEnquiry.getEmail()) && !whiteEmailList.contains(adwebEnquiry.getEmail().toLowerCase())) {
                isBlackFlag = dealShortSameEmail(adwebEnquiry, blackEmailList, adwebSite, siteBlackEmailList);
            }

            // 判断十分钟和一天内同个站点是否有相同的Ip
            if (StringUtils.isNotBlank(adwebEnquiry.getFromIp()) && !whiteIpList.contains(adwebEnquiry.getFromIp())) {
                isBlackFlag = dealShortSameIp(adwebEnquiry, blackIpList, adwebSite, siteBlackIpList);
            }
            if (isBlackFlag) {
                continue;
            }
            adwebEnquiry.setWasteEnquiry(0);
            adwebEnquiry.setUserEffective(2);
            // 此处为正常询盘，清除疑似垃圾询盘可能性
            isJudgeWasteEnquiry = null;
            log.info("询盘id是:{}, 站点code是:{}, 不是垃圾询盘", adwebEnquiry.getId(), adwebEnquiry.getSiteCode());
        }

        //判断最后一个询盘是否为垃圾询盘
        isPreviousOneWasteEnquiry(blackEmailList, blackIpList, isJudgeWasteEnquiry);

        //更新redis
        //站点
        if (CollectionUtils.isNotEmpty(siteBlackEmailList)) {
            adwebRedisUtil.set(SiteBlackEmailKey + "::" + adwebSite.getId(), siteBlackEmailList, 86400);
        }
        if (CollectionUtils.isNotEmpty(siteBlackIpList)) {
            adwebRedisUtil.set(SiteBlackIpKey + "::" + adwebSite.getId(), siteBlackIpList, 86400);
        }
        if (CollectionUtils.isNotEmpty(siteWhiteEmailList)) {
            adwebRedisUtil.set(SiteWhiteEmailListKey + "::" + adwebSite.getId(), siteWhiteEmailList, 86400);
        }
        if (CollectionUtils.isNotEmpty(siteWhiteIpList)) {
            adwebRedisUtil.set(SiteWhiteIpListKey + "::" + adwebSite.getId(), siteWhiteIpList, 86400);
        }
        //公共
        if (CollectionUtils.isNotEmpty(publicBlackEmailList)) {
            adwebRedisUtil.set(BlackEmailKey, publicBlackEmailList, 86400);
        }
        if (CollectionUtils.isNotEmpty(publicBlackIpList)) {
            adwebRedisUtil.set(BlackIpKey, publicBlackIpList, 86400);
        }
        if (CollectionUtils.isNotEmpty(publicWhiteEmailList)) {
            adwebRedisUtil.set(WhiteEmailListKey, publicWhiteEmailList, 86400);
        }
        if (CollectionUtils.isNotEmpty(publicWhiteIpList)) {
            adwebRedisUtil.set(WhiteIpListKey, publicWhiteIpList, 86400);
        }
    }

    private boolean validateWordLength(String text) {
        if (StringUtil.isEmpty(text)) {
            return false;
        }
        int maxWordLength = EnglishAnalyzer.getLongestSize(text);
        int limit;
        SysDictItem dictItem = dictService.getDictItemByCodeAndText("max_word_length", "default");
        if (dictItem == null || StringUtil.isEmpty(dictItem.getItemValue())) {
            limit = 50;
        } else {
            limit = Integer.parseInt(dictItem.getItemValue());
        }
        return (maxWordLength > limit);
    }


    private List<String> parser(String text) {
        Pattern pattern1 = Pattern.compile("(https?|ftp|file)://([-a-zA-Z0-9]+\\.)+[a-zA-Z0-9]+");
        List<String> domainPatterns = getFormKeys("enquiry_domain_pattern");
        String domainPattern = "";
        if (CollectionUtils.isNotEmpty(domainPatterns)) {
            domainPattern = domainPatterns.get(0);
        }
        if (StringUtil.isEmpty(domainPattern)) {
            domainPattern = "([-a-zA-Z0-9]+\\.)+(com|cn|net|org|edu|hk|fr|de|uk|eu|tw|ph|my|id|in|ind|co|pk|mx|us" +
                    "|ve|ar|eg|online|xyz|me|jp|ly|baz|io|cc|tv|club|xxx|host|ltd|vip|work|fit|pub|love|xin|info|pro|post|coop|int|jobs|cat|travel" +
                    "|ru|onion|site|it)+";
        } else {
            domainPattern = "([-a-zA-Z0-9]+\\.)+" + domainPattern;
        }
        Pattern pattern2 = Pattern.compile(domainPattern);

        // 邮箱正则
        Pattern pattern3 = Pattern.compile("[a-zA-Z0-9_\\-\\.]+@[a-zA-Z0-9_\\-\\.]+\\.[a-zA-Z0-9_\\-\\.]+");

        //判断正文中是否存在邮箱
        Matcher matcher = pattern3.matcher(text);
        List<String> emailList = new ArrayList<>();
        while (matcher.find()) {
            String keyWord = matcher.group();
            String lastWord = keyWord.substring(keyWord.length() - 1);
            if (".".equals(lastWord)) {
                keyWord = keyWord.substring(0, keyWord.length() - 1);
            }
            emailList.add(keyWord);
            if (keyWord.lastIndexOf("@") > -1) {
                emailList.add(keyWord.substring(keyWord.lastIndexOf("@") + 1));
                emailList.add(keyWord.substring(0, keyWord.lastIndexOf("@")));
            }
        }

        List<String> urls = new ArrayList<>();

        Matcher matcher1 = pattern1.matcher(text);
        while (matcher1.find()) {
            urls.add(matcher1.group());
        }

        Matcher matcher2 = pattern2.matcher(text);
        while (matcher2.find()) {
            urls.add(matcher2.group());
        }

        // 如果邮箱和 URL 都存在，并且 URL 中不包含 http 和 https，则从 URL 中删除邮箱
        if (CollectionUtils.isNotEmpty(emailList)) {
            Set<String> urlSet = new HashSet<>(urls);
            urlSet.removeAll(emailList.stream()
                    .filter(email -> urlSet.contains(email) && !email.contains("http") && !email.contains("https"))
                    .collect(Collectors.toSet()));
            urls = new ArrayList<>(urlSet);
        }

        urls = urls.stream().distinct().collect(Collectors.toList());
        return urls;
    }

    /**
     * 判断是否时垃圾询盘
     */
    private void isPreviousOneWasteEnquiry(List<String> blackEmailList, List<String> blackIpList, AdwebEnquiry isJudgeWasteEnquiry) {
        if (isJudgeWasteEnquiry != null && StringUtils.isNotBlank(isJudgeWasteEnquiry.getSiteCode())) {
            log.info("上一封邮件为垃圾询盘,处理中...");
            boolean emailFlag = false;
            String isJudgeWasteEnquiryEmail = isJudgeWasteEnquiry.getEmail().toLowerCase();
            if (StringUtils.isNotBlank(isJudgeWasteEnquiryEmail) && CollectionUtils.isNotEmpty(blackEmailList)) {
                for (String blackEmail : blackEmailList) {
                    if (isJudgeWasteEnquiry.getEmail().equals(blackEmail)) {
                        emailFlag = false;
                        break;
                    } else if (blackEmail.contains("*")) {
                        String generalBlackEmail = blackEmail.substring(1, blackEmail.length() - 1 - 1);
                        if (isJudgeWasteEnquiry.getEmail().contains(generalBlackEmail)) {
                            emailFlag = false;
                            break;
                        }
                    } else {
                        emailFlag = true;
                    }
                }
            }

            boolean ipFlag = StringUtils.isNotBlank(isJudgeWasteEnquiry.getFromIp()) && blackIpList != null && !blackIpList.contains(isJudgeWasteEnquiry.getFromIp());

            //该分支用于判断上一封垃圾询盘 不在邮箱黑名单中
            if (emailFlag) {
                Integer notBlackEmailWasteListCount = null;
                if (adwebRedisUtil.hasKey(NotBlackEmailWasteEnquiryKey + isJudgeWasteEnquiry.getEmail())) {
                    notBlackEmailWasteListCount = (Integer) adwebRedisUtil.get(NotBlackEmailWasteEnquiryKey + isJudgeWasteEnquiry.getEmail()) + 1;
                } else {
                    notBlackEmailWasteListCount = 1;
                }
                adwebRedisUtil.set(NotBlackEmailWasteEnquiryKey + isJudgeWasteEnquiry.getEmail(), notBlackEmailWasteListCount, 60L * 60 * 24 * emailNotBlackListDate);

                //该分支用于判断是否超过
                if (notBlackEmailWasteListCount > emailNotBlackListNum) {
                    AdwebPublicBlackEmail blackEmail = new AdwebPublicBlackEmail(isJudgeWasteEnquiry.getEmail(), NumConstant.ONE, NumConstant.ZERO);
                    if (adwebPublicBlackEmailService.count(new QueryWrapper<AdwebPublicBlackEmail>().eq("email", isJudgeWasteEnquiry.getEmail()).ne("status", 0)) == 0) {
                        adwebPublicBlackEmailService.save(blackEmail);
                        blackEmailList.add(isJudgeWasteEnquiry.getEmail());
                        log.info("询盘id是:{}, 站点code是:{}, 检测重复，已标记邮箱, 邮箱是:{}", isJudgeWasteEnquiry.getId(), isJudgeWasteEnquiry.getSiteCode(), isJudgeWasteEnquiry.getEmail());
                    }
                    adwebRedisUtil.del(NotBlackEmailWasteEnquiryKey + isJudgeWasteEnquiry.getEmail());
                }
            }
            if (ipFlag) {
                Integer notBlackIpWasteListCount = null;
                if (adwebRedisUtil.hasKey(NotBlackIpWasteEnquiryKey + isJudgeWasteEnquiry.getFromIp())) {
                    notBlackIpWasteListCount = (Integer) adwebRedisUtil.get(NotBlackIpWasteEnquiryKey + isJudgeWasteEnquiry.getFromIp()) + 1;
                } else {
                    notBlackIpWasteListCount = 1;
                }
                adwebRedisUtil.set(NotBlackIpWasteEnquiryKey + isJudgeWasteEnquiry.getFromIp(), notBlackIpWasteListCount, 60L * 60 * 24 * ipNotBlackListDate);

                //该分支用于判断是否出现超过
                if (notBlackIpWasteListCount > ipNotBlackListNum) {
                    AdwebPublicBlackIp blackIp = new AdwebPublicBlackIp(isJudgeWasteEnquiry.getFromIp(), NumConstant.ONE, NumConstant.ZERO);
                    if (adwebPublicBlackIpService.count(new QueryWrapper<AdwebPublicBlackIp>().eq("ip", isJudgeWasteEnquiry.getFromIp()).ne("status", 0)) == 0) {
                        adwebPublicBlackIpService.save(blackIp);
                        blackIpList.add(isJudgeWasteEnquiry.getFromIp());
                        log.info("询盘id是:{}, 站点code是:{}, 检测重复，已标记ip, ip是:{}", isJudgeWasteEnquiry.getId(), isJudgeWasteEnquiry.getSiteCode(), isJudgeWasteEnquiry.getFromIp());
                    }
                    adwebRedisUtil.del(NotBlackIpWasteEnquiryKey + isJudgeWasteEnquiry.getFromIp());
                }
            }
        }
    }

    /**
     * 当同步询盘拉取时，处理同个邮箱或者同个ip的询盘达到一定数量后置为黑名单
     * 如果是公共黑名单
     */
    private void dealMultipleRepeatInfoEnquiry(List<String> siteBlackEmailList, List<String> siteBlackIpList, AdwebEnquiry isJudgeWasteEnquiry, AdwebSite adwebSite) {
        if (isJudgeWasteEnquiry != null && StringUtils.isNotBlank(isJudgeWasteEnquiry.getSiteCode())) {
            log.info("上一封邮件为垃圾询盘,处理中...");
            boolean emailFlag = false;
            String isJudgeWasteEnquiryEmail = isJudgeWasteEnquiry.getEmail().toLowerCase();
            if (StringUtils.isNotBlank(isJudgeWasteEnquiryEmail) && CollectionUtils.isNotEmpty(siteBlackEmailList)) {
                for (String blackEmail : siteBlackEmailList) {
                    if (isJudgeWasteEnquiry.getEmail().equals(blackEmail)) {
                        emailFlag = false;
                        break;
                    } else if (blackEmail.contains("*")) {
                        String generalBlackEmail = blackEmail.substring(1, blackEmail.length() - 1 - 1);
                        if (isJudgeWasteEnquiry.getEmail().contains(generalBlackEmail)) {
                            emailFlag = false;
                            break;
                        }
                    } else {
                        emailFlag = true;
                    }
                }
            }

            boolean ipFlag = StringUtils.isNotBlank(isJudgeWasteEnquiry.getFromIp()) && siteBlackIpList != null && !siteBlackIpList.contains(isJudgeWasteEnquiry.getFromIp());

            //该分支用于判断上一封垃圾询盘 不在邮箱黑名单中
            if (emailFlag) {
                Integer notBlackEmailWasteListCount = null;
                if (adwebRedisUtil.hasKey(NotBlackEmailWasteSiteEnquiryKey + adwebSite.getId() + "::" + isJudgeWasteEnquiry.getEmail())) {
                    notBlackEmailWasteListCount = (Integer) adwebRedisUtil.get(NotBlackEmailWasteSiteEnquiryKey + adwebSite.getId() + "::" + isJudgeWasteEnquiry.getEmail()) + 1;
                } else {
                    notBlackEmailWasteListCount = 1;
                }
                adwebRedisUtil.set(NotBlackEmailWasteSiteEnquiryKey + adwebSite.getId() + "::" + isJudgeWasteEnquiry.getEmail(), notBlackEmailWasteListCount, 60L * 60 * 24 * emailNotBlackListDate);

                //该分支用于判断是否超过
                if (notBlackEmailWasteListCount > emailNotBlackListNum) {
                    if (enquirySiteBlackEmailService.count(new QueryWrapper<AdwebSiteBlackEmail>().eq("email", isJudgeWasteEnquiry.getEmail()).ne("status", 0).eq("site_id", adwebSite.getId()).eq("black_or_white", 0)) == 0) {
                        siteBlackEmailList.add(isJudgeWasteEnquiry.getEmail());
                        log.info("询盘id是:{}, 站点code是:{}, 检测重复，已标记邮箱, 邮箱是:{}", isJudgeWasteEnquiry.getId(), isJudgeWasteEnquiry.getSiteCode(), isJudgeWasteEnquiry.getEmail());
                    }
                    EffectiveEnquiryParamDto effectiveEnquiryParamDto = new EffectiveEnquiryParamDto();
                    effectiveEnquiryParamDto.setSiteId(adwebSite.getId());
                    effectiveEnquiryParamDto.setSiteCode(adwebSite.getCode());
                    effectiveEnquiryParamDto.setWasteEnquirySeason(isJudgeWasteEnquiry.getEmail());
                    enquirySiteBlackEmailService.addBlackEmailByContent(effectiveEnquiryParamDto);
                    adwebRedisUtil.del(NotBlackEmailWasteSiteEnquiryKey + adwebSite.getId() + "::" + isJudgeWasteEnquiry.getEmail());
                }
            }
            if (ipFlag) {
                Integer notBlackIpWasteListCount = null;
                if (adwebRedisUtil.hasKey(NotSiteBlackIpWasteEnquiryKey + adwebSite.getId() + "::" + isJudgeWasteEnquiry.getFromIp())) {
                    notBlackIpWasteListCount = (Integer) adwebRedisUtil.get(NotSiteBlackIpWasteEnquiryKey + adwebSite.getId() + "::" + isJudgeWasteEnquiry.getFromIp()) + 1;
                } else {
                    notBlackIpWasteListCount = 1;
                }
                adwebRedisUtil.set(NotSiteBlackIpWasteEnquiryKey + adwebSite.getId() + "::" + isJudgeWasteEnquiry.getFromIp(), notBlackIpWasteListCount, 60L * 60 * 24 * ipNotBlackListDate);

                //该分支用于判断是否出现超过
                if (notBlackIpWasteListCount > ipNotBlackListNum) {
                    if (adwebSiteBlackIpService.count(new QueryWrapper<AdwebSiteBlackIp>().eq("ip", isJudgeWasteEnquiry.getFromIp()).ne("status", 0).eq("site_id", adwebSite.getId()).eq("black_or_white", 0)) == 0) {
                        siteBlackIpList.add(isJudgeWasteEnquiry.getFromIp());
                        log.info("询盘id是:{}, 站点code是:{}, 检测重复，已标记ip, ip是:{}", isJudgeWasteEnquiry.getId(), isJudgeWasteEnquiry.getSiteCode(), isJudgeWasteEnquiry.getFromIp());
                    }
                    EffectiveEnquiryParamDto effectiveEnquiryParamDto = new EffectiveEnquiryParamDto();
                    effectiveEnquiryParamDto.setWasteEnquirySeason(isJudgeWasteEnquiry.getFromIp());
                    effectiveEnquiryParamDto.setSiteId(adwebSite.getId());
                    effectiveEnquiryParamDto.setSiteCode(adwebSite.getCode());
                    adwebSiteBlackIpService.addBlackIpByContent(effectiveEnquiryParamDto);
                    adwebRedisUtil.del(NotSiteBlackIpWasteEnquiryKey + adwebSite.getId() + "::" + isJudgeWasteEnquiry.getFromIp());
                }
            }
        }
    }

    /**
     * 当同步询盘拉取时，处理10分钟或一天同个邮箱的询盘达到一定数量后置为黑名单
     */
    private boolean dealShortSameEmail(AdwebEnquiry adwebEnquiry, List<String> blackEmailList, AdwebSite adwebSite, List<String> siteBlackEmailList) {
        Integer tenMin = null;
        String TenMinKey = SiteEmailTenMinKey + adwebSite.getId() + "::" + adwebEnquiry.getEmail();
        String oneDayKey = SiteEmailOneDayKey + adwebSite.getId() + "::" + adwebEnquiry.getEmail();
        if (adwebRedisUtil.hasKey(TenMinKey)) {
            tenMin = (Integer) adwebRedisUtil.get(TenMinKey) + 1;
        } else {
            tenMin = 1;
        }
        adwebRedisUtil.set(TenMinKey, tenMin, 10 * 60);

        if (tenMin > emailTenMinNum) {
            adwebEnquiry.setWasteEnquiry(1);
            adwebEnquiry.setUserEffective(0);
            adwebEnquiry.setWasteEnquiryType("email");
            adwebEnquiry.setEffectiveReason("系统操作-通过十分钟内重复邮箱检测到垃圾询盘-" + adwebEnquiry.getEmail());
            log.info("询盘id是:{}, 站点code是:{}, 通过——十分钟内—重复邮箱—检测到垃圾询盘",
                    adwebEnquiry.getId(), adwebEnquiry.getSiteCode());
            if (enquirySiteBlackEmailService.count(new QueryWrapper<AdwebSiteBlackEmail>().eq("email", adwebEnquiry.getEmail()).ne("status", 0).eq("site_id", adwebSite.getId()).eq("black_or_white", 0)) == 0) {
                siteBlackEmailList.add(adwebEnquiry.getEmail());
                blackEmailList.add(adwebEnquiry.getEmail());
                log.info("询盘id是:{}, 站点code是:{}, 检测十分钟内重复，已标记邮箱, 邮箱是:{}", adwebEnquiry.getId(), adwebEnquiry.getSiteCode(), adwebEnquiry.getEmail());
            }
            // 存储到数据库中
            EffectiveEnquiryParamDto effectiveEnquiryParamDto = new EffectiveEnquiryParamDto();
            effectiveEnquiryParamDto.setSiteId(adwebSite.getId());
            effectiveEnquiryParamDto.setSiteCode(adwebSite.getCode());
            effectiveEnquiryParamDto.setWasteEnquirySeason(adwebEnquiry.getEmail());
            enquirySiteBlackEmailService.addBlackEmailByContent(effectiveEnquiryParamDto);
            // 清除map中的数据
            adwebRedisUtil.del(TenMinKey);
            adwebRedisUtil.del(oneDayKey);
            return true;
        }

        //如果10分钟内发送了则1天用判断了
        Integer oneDay = null;
        if (adwebRedisUtil.hasKey(oneDayKey)) {
            oneDay = (Integer) adwebRedisUtil.get(oneDayKey) + 1;
        } else {
            oneDay = 1;
        }
        adwebRedisUtil.set(oneDayKey, oneDay, 24 * 60 * 60);

        if (oneDay > emailOneDayNum) {
            adwebEnquiry.setWasteEnquiry(1);
            adwebEnquiry.setUserEffective(0);
            adwebEnquiry.setWasteEnquiryType("email");
            adwebEnquiry.setEffectiveReason("系统操作-通过一天内重复邮箱检测到垃圾询盘-" + adwebEnquiry.getEmail());
            log.info("询盘id是:{}, 站点code是:{}, 通过——一天内—重复邮箱—检测到垃圾询盘",
                    adwebEnquiry.getId(), adwebEnquiry.getSiteCode());
            log.info("'--------dealShortSameEmail -----'===>adwebEnquiry.getEmail():{}", adwebEnquiry.getEmail());
            log.info("'--------dealShortSameEmail -----'===>adwebSite.getId():{}", adwebSite.getId());
            if (enquirySiteBlackEmailService.count(new QueryWrapper<AdwebSiteBlackEmail>().eq("email", adwebEnquiry.getEmail()).ne("status", 0).eq("site_id", adwebSite.getId()).eq("black_or_white", 0)) == 0) {
                siteBlackEmailList.add(adwebEnquiry.getEmail());
                blackEmailList.add(adwebEnquiry.getEmail());
                log.info("询盘id是:{}, 站点code是:{}, 检测十分钟内重复，已标记邮箱, 邮箱是:{}", adwebEnquiry.getId(), adwebEnquiry.getSiteCode(), adwebEnquiry.getEmail());
            }
            // 存储到数据库中
            EffectiveEnquiryParamDto effectiveEnquiryParamDto = new EffectiveEnquiryParamDto();
            effectiveEnquiryParamDto.setSiteId(adwebSite.getId());
            effectiveEnquiryParamDto.setSiteCode(adwebSite.getCode());
            effectiveEnquiryParamDto.setWasteEnquirySeason(adwebEnquiry.getEmail());
            enquirySiteBlackEmailService.addBlackEmailByContent(effectiveEnquiryParamDto);
            // 清除map中的数据
            adwebRedisUtil.del(oneDayKey);
            return true;
        }
        return false;
    }

    /**
     * 当同步询盘拉取时，处理同个ip的询盘达到一定数量后置为黑名单
     * 如果是公共黑名单
     */
    private boolean dealShortSameIp(AdwebEnquiry adwebEnquiry, List<String> blackIpList, AdwebSite adwebSite, List<String> siteBlackIpList) {
        Integer tenMin = null;
        String tenMinKey = SiteIpTenMinKey + adwebSite.getId() + "::" + adwebEnquiry.getFromIp();
        String oneDayKey = SiteIpOneDayKey + adwebSite.getId() + "::" + adwebEnquiry.getFromIp();
        if (adwebRedisUtil.hasKey(tenMinKey)) {
            tenMin = (Integer) adwebRedisUtil.get(tenMinKey) + 1;
        } else {
            tenMin = 1;
        }
        adwebRedisUtil.set(tenMinKey, tenMin, 10 * 60);
        if (tenMin > ipTenMinNum) {
            adwebEnquiry.setWasteEnquiry(1);
            adwebEnquiry.setUserEffective(0);
            adwebEnquiry.setWasteEnquiryType("ip");
            adwebEnquiry.setEffectiveReason("系统操作-通过十分钟内重复IP检测到垃圾询盘-" + adwebEnquiry.getFromIp());
            log.info("询盘id是:{}, 站点code是:{}, 通过——十分钟内—重复IP—检测到垃圾询盘", adwebEnquiry.getId(), adwebEnquiry.getSiteCode());
            if (adwebSiteBlackIpService.count(new QueryWrapper<AdwebSiteBlackIp>().eq("ip", adwebEnquiry.getFromIp()).ne("status", 0).eq("site_id", adwebSite.getId()).eq("black_or_white", 0)) == 0) {
                siteBlackIpList.add(adwebEnquiry.getFromIp());
                blackIpList.add(adwebEnquiry.getFromIp());
                log.info("询盘id是:{}, 站点code是:{}, 检测十分钟内重复，已标记ip, ip是:{}", adwebEnquiry.getId(), adwebEnquiry.getSiteCode(), adwebEnquiry.getFromIp());
            }
            // 存储到数据库中
            EffectiveEnquiryParamDto effectiveEnquiryParamDto = new EffectiveEnquiryParamDto();
            effectiveEnquiryParamDto.setWasteEnquirySeason(adwebEnquiry.getFromIp());
            effectiveEnquiryParamDto.setSiteId(adwebSite.getId());
            effectiveEnquiryParamDto.setSiteCode(adwebSite.getCode());
            adwebSiteBlackIpService.addBlackIpByContent(effectiveEnquiryParamDto);
            // 清除map中的数据
            adwebRedisUtil.del(tenMinKey);
            adwebRedisUtil.del(oneDayKey);
            return true;
        }

        Integer oneDay = null;
        if (adwebRedisUtil.hasKey(oneDayKey)) {
            oneDay = (Integer) adwebRedisUtil.get(oneDayKey) + 1;
        } else {
            oneDay = 1;
        }
        adwebRedisUtil.set(oneDayKey, oneDay, 24 * 60 * 60);
        if (oneDay > ipOneDayNum) {
            adwebEnquiry.setWasteEnquiry(1);
            adwebEnquiry.setUserEffective(0);
            adwebEnquiry.setWasteEnquiryType("ip");
            adwebEnquiry.setEffectiveReason("系统操作-通过一天内重复IP检测到垃圾询盘-" + adwebEnquiry.getFromIp());
            log.info("询盘id是:{}, 站点code是:{}, 通过——一天内—重复IP—检测到垃圾询盘", adwebEnquiry.getId(), adwebEnquiry.getSiteCode());
            if (adwebSiteBlackIpService.count(new QueryWrapper<AdwebSiteBlackIp>().eq("ip", adwebEnquiry.getFromIp()).ne("status", 0).eq("site_id", adwebSite.getId()).eq("black_or_white", 0)) == 0) {
                siteBlackIpList.add(adwebEnquiry.getFromIp());
                blackIpList.add(adwebEnquiry.getFromIp());
                log.info("询盘id是:{}, 站点code是:{}, 检测一天内重复，已标记ip, ip是:{}", adwebEnquiry.getId(), adwebEnquiry.getSiteCode(), adwebEnquiry.getFromIp());
            }
            // 存储到数据库中
            EffectiveEnquiryParamDto effectiveEnquiryParamDto = new EffectiveEnquiryParamDto();
            effectiveEnquiryParamDto.setWasteEnquirySeason(adwebEnquiry.getFromIp());
            effectiveEnquiryParamDto.setSiteId(adwebSite.getId());
            effectiveEnquiryParamDto.setSiteCode(adwebSite.getCode());
            adwebSiteBlackIpService.addBlackIpByContent(effectiveEnquiryParamDto);
            // 清除map中的数据
            adwebRedisUtil.del(oneDayKey);
            return true;
        }
        return false;
    }

    /**
     * 判断是否是在黑名单中
     *
     * @param adwebEnquiryList 询盘列表
     */
    private void judgeBlacklist(List<AdwebEnquiry> adwebEnquiryList) {
        for (AdwebEnquiry enquiry : adwebEnquiryList) {
            boolean isBlackEnquiry = adwebEnquiryBlacklistService.isBlackEnquiry(enquiry);
            if (isBlackEnquiry) {
                enquiry.setStatus(0);
                enquiry.setPushStatus(2);
            }
        }
    }

    @Override
    public void returnSalesperson(String siteCode, String inquiryId, String sales) {
        log.info("返回跟进人名称开始");
        //获取站点
        QueryWrapper<AdwebSite> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code", siteCode);
        AdwebSite adwebSite = adwebSiteService.getOne(queryWrapper);

        RestTemplate restTemplate = new RestTemplate();
        String url = adwebSite.getDomain() + "/wp-json/inquiry/v1/add-sales";
        log.info("请求地址{}", url);
        // 如果需要传递参数
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json");
        // 构建请求体，将 recordId 和 name 作为参数传递
        String requestBody = "{ \"inquiryId\": \"" + inquiryId + "\", \"sales\": \"" + sales + "\" }";
        log.info("请求参数{}", requestBody);
        HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);

        // 发送请求
        restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
        log.info("返回跟进人名称结束");
    }

    /**
     * 根据地区更新询盘跟进人
     */
    @Override
    public void updatePrincipalUidByRegion(Integer siteId) {
        List<Integer> siteIds = adwebSiteService.getAllSiteIdByParentId(siteId);
        adwebEnquiryMapper.updatePrincipalUidByRegion(siteId, siteIds);
    }

    /**
     * 更改询盘用户有效性
     *
     * @return
     */
    @Override
    public boolean updateUserEffective(EffectiveEnquiryParamDto effectiveEnquiryParamDto) {
        String id = effectiveEnquiryParamDto.getId();
        Integer userEffective = effectiveEnquiryParamDto.getUserEffective();
        if (userEffective == null || StringUtil.isEmpty(id)) {
            return false;
        }

        List<String> idList = Arrays.asList(id.split(","));
        if (CollectionUtils.isEmpty(idList)) {
            return false;
        }

        UpdateWrapper<AdwebEnquiry> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("id", idList);
        // 用户有效性  0：无效 1：有效   2 : 待定 取自字典表
        updateWrapper.set("user_effective", userEffective);
        // 0：不是；1：是
        if (userEffective.equals(0)) {  // 垃圾询盘
            String wasteEnquiryType = effectiveEnquiryParamDto.getWasteEnquiryType();
            String wasteEnquirySeason = effectiveEnquiryParamDto.getWasteEnquirySeason();
            updateWrapper.set("waste_enquiry", 1);
            updateWrapper.set("waste_enquiry_type", wasteEnquiryType);

            //特殊处理垃圾询盘是邮箱或者ip
            if (wasteEnquiryType.equals("ip")) {
                updateWrapper.set("effective_reason", "人工操作-ip-" + wasteEnquirySeason);
                adwebSiteBlackIpService.addBlackIpByContent(effectiveEnquiryParamDto);
            }
            if (wasteEnquiryType.equals("email")) {
                updateWrapper.set("effective_reason", "人工操作-邮箱-" + wasteEnquirySeason);
                enquirySiteBlackEmailService.addBlackEmailByContent(effectiveEnquiryParamDto);
            }
            if (wasteEnquiryType.equals("keyword")) {
                updateWrapper.set("effective_reason", "人工操作-关键词-" + wasteEnquirySeason);
                adwebSiteEnquiryRuleService.addBlackKeywordByContent(effectiveEnquiryParamDto);
            }
            if (wasteEnquiryType.equals("other")) {
                updateWrapper.set("effective_reason", "人工操作-其他-" + wasteEnquirySeason);
            }
        } else {  // 有效询盘
            updateWrapper.set("waste_enquiry", 0);
            updateWrapper.set("effective_reason", "人工操作");
            updateWrapper.set("waste_enquiry_type", "");
        }
        this.update(updateWrapper);

        if (userEffective.equals(0)) {
            return true;
        }

        // 有效询盘发送邮件
        try {
            List<AdwebEnquiry> enquiryList = this.list(new LambdaQueryWrapper<AdwebEnquiry>().in(AdwebEnquiry::getId, idList));
            if (CollectionUtils.isNotEmpty(enquiryList)) {
                AdwebSite adwebSite = adwebSiteService.getOne(new QueryWrapper<AdwebSite>().eq("code", enquiryList.get(0).getSiteCode()));
                if (adwebSite != null) {

                    Map<String, String> principalEmailMap = new HashMap<>();

                    //判断是否为产品询盘
                    for (AdwebEnquiry adwebEnquiry : enquiryList) {
                        if (StringUtils.isNotBlank(adwebEnquiry.getCartItems())) {
                            adwebEnquiry.setExistProductEnquiry(1);  // 产品询盘
                        }
                    }

                    // 判断是否为联系我们询盘
                    for (AdwebEnquiry adwebEnquiry : enquiryList) {
                        List<DictModel> contactEnquiryWebsites = dictService.queryDictItemsByCode("send_contact_enquiry_website");
                        List<String> contactEnquiryCodes = contactEnquiryWebsites.stream().map(DictModel::getValue).toList();
                        if (contactEnquiryCodes.contains(adwebSite.getCode())) {
                            if (StringUtils.isNotBlank(adwebEnquiry.getFromPage()) && adwebEnquiry.getFromPage().contains("contact")) {
                                adwebEnquiry.setExistContactEnquiry(1);
                            }
                        }
                    }

                    //获取子账户
                    List<String> subAccountIdList = masterSubAccountRelationService.getSubAccountIdByMaster(String.valueOf(adwebSite.getUid()));
                    log.info("获取的子账户id：{}", FastJsonUtil.toJSONString(subAccountIdList));
                    if (CollectionUtils.isNotEmpty(subAccountIdList)) {
                        subAccountIdList.add(String.valueOf(adwebSite.getUid()));
                        List<SysUser> principalEmailList = sysUserService.list(new QueryWrapper<SysUser>().in("id", subAccountIdList).eq("del_flag", 0).isNotNull("email").ne("email", "").select("id", "email"));
                        if (CollectionUtils.isNotEmpty(principalEmailList)) {
                            principalEmailMap = principalEmailList.stream().collect(Collectors.toMap(SysUser::getId, SysUser::getEmail));

                        }
                    }
                    sendValidateEmail(enquiryList, adwebSite, principalEmailMap);
                }
            }
        } catch (Exception e) {
            log.error("推送发送询盘邮件的消息失败", e);
        }
        return true;
    }
}
