package com.pig4cloud.pig.marketing.service.impl;


import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
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.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pig.admin.api.dto.SysPublicParamDTO;
import com.pig4cloud.pig.admin.api.feign.RemoteParamService;
import com.pig4cloud.pig.common.core.exception.BusinessException;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.core.util.ip.IPUtils;
import com.pig4cloud.pig.marketing.api.dto.app.*;
import com.pig4cloud.pig.marketing.api.entity.*;
import com.pig4cloud.pig.marketing.api.vo.app.*;
import com.pig4cloud.pig.marketing.mapper.*;
import com.pig4cloud.pig.marketing.service.MarketingAppsService;
import com.pig4cloud.pig.marketing.service.MarketingConfigService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import static com.pig4cloud.pig.marketing.api.MarketingConfigConstants.*;

/**
 * @author: lwh
 * @date: 2025-07-22
 * @description: 应用列表Service实现类
 */
@Slf4j
@Service
@AllArgsConstructor
public class MarketingAppsServiceImpl implements MarketingAppsService {


	// 从配置文件读取URL
//	@Value("${marketing.app.url}")
	private static final String getAppListUrl = "http://192.168.3.17:2888/ipa/getApps";

	// 从配置文件读取accessKey
//	@Value("${marketing.app.access-key}")
	private static final String accessKey = "4ea5ba93-d222-45dc-862a-1c7fc7789d11";

	private final MarketingAppsMapper appsMapper;

	private final MarketingAppsIpMapper appsIpMapper;

	private final MarketingAppsDomainMapper appsDomainMapper;

	private final MarketingGroupDomainMapper groupDomainMapper;

	private final MarketingConfigGroupMapper groupMapper;

	private final MarketingGroupIpMapper groupIpMapper;

	private final RemoteParamService remoteParamService;




	/**
	 * 分页查询应用列表
	 * @param reqDto 查询参数
	 * @return Page
	 */
	@Override
	public Page pageMarketingApps(PageMarketingAppsDTO reqDto, Boolean status){
		Page page = appsMapper.selectPage(new Page(reqDto.getCurrent(), reqDto.getSize()),
				Wrappers.<MarketingApps>lambdaQuery()
						.eq(MarketingApps::getStatus, status)
						.like(StrUtil.isNotBlank(reqDto.getAppId()), MarketingApps::getAppId, reqDto.getAppId())
						.like(StrUtil.isNotBlank(reqDto.getAppName()), MarketingApps::getAppName, reqDto.getAppName())
						.like(StrUtil.isNotBlank(reqDto.getDomainType()), MarketingApps::getDomainType, reqDto.getDomainType())
						.like(StrUtil.isNotBlank(reqDto.getRemark()), MarketingApps::getRemark, reqDto.getRemark())
		);

		List<MarketingApps> records = page.getRecords();
		List<PageMarketingAppsVO> appsVOList = new ArrayList<>();
		for (MarketingApps app : records) {
			PageMarketingAppsVO appsVO = new PageMarketingAppsVO();
			BeanUtils.copyProperties(app, appsVO);
			// 组装IP
			List<MarketingAppsIp> ips = appsIpMapper.selectList(new QueryWrapper<MarketingAppsIp>().eq("app_id", app.getId()));
			List<MarketingAppsIpVO> ipVOList = new ArrayList<>();
			for (MarketingAppsIp ip : ips) {
				MarketingAppsIpVO ipVO = new MarketingAppsIpVO();
				BeanUtils.copyProperties(ip, ipVO);
				if (ip.getGroupId() != null){
					MarketingConfigGroup group = groupMapper.selectById(ip.getGroupId());
					if (group != null)
						ipVO.setGroupName(group.getGroupName());
				}
				ipVOList.add(ipVO);
			}
			appsVO.setIps(ipVOList);
			// 组装域名

			List<MarketingAppsDomain> domains = appsDomainMapper.selectList(new QueryWrapper<MarketingAppsDomain>().eq("app_id", app.getId()));
			ArrayList<MarketingAppsDomainVO> domainVOList = new ArrayList<>();
			for (MarketingAppsDomain domain : domains) {
				MarketingAppsDomainVO domainVO = new MarketingAppsDomainVO();
				BeanUtils.copyProperties(domain, domainVO);
				if (domain.getGroupId() != null){
					MarketingConfigGroup group = groupMapper.selectById(domain.getGroupId());
					if (group != null)
						domainVO.setGroupName(group.getGroupName());
				}
				domainVOList.add(domainVO);
			}
			appsVO.setDomains(domainVOList);
			appsVOList.add(appsVO);
		}

		page.setRecords(appsVOList);
		return page;
	}

	/**
	 * 根据ID获取应用详情
	 * @param id 应用ID
	 * @return 应用详情
	 */
	@Override
	public PageMarketingAppsVO getMarketingAppById(Long id) {
		MarketingApps app = appsMapper.selectById(id);
		if (app == null){
			throw new BusinessException("应用不存在");
		}
		PageMarketingAppsVO appsVO = new PageMarketingAppsVO();
		BeanUtils.copyProperties(app, appsVO);
		// 组装IP
		List<MarketingAppsIp> ips = appsIpMapper.selectList(new QueryWrapper<MarketingAppsIp>().eq("app_id", app.getId()));
		List<MarketingAppsIpVO> ipVOList = new ArrayList<>();
		for (MarketingAppsIp ip : ips) {
			MarketingAppsIpVO ipVO = new MarketingAppsIpVO();
			BeanUtils.copyProperties(ip, ipVO);
			if (ip.getGroupId() != null){
				MarketingConfigGroup group = groupMapper.selectById(ip.getGroupId());
				if (group != null)
					ipVO.setGroupName(group.getGroupName());
			}
			ipVOList.add(ipVO);
		}
		appsVO.setIps(ipVOList);
		// 组装域名

		List<MarketingAppsDomain> domains = appsDomainMapper.selectList(new QueryWrapper<MarketingAppsDomain>().eq("app_id", app.getId()));
		ArrayList<MarketingAppsDomainVO> domainVOList = new ArrayList<>();
		for (MarketingAppsDomain domain : domains) {
			MarketingAppsDomainVO domainVO = new MarketingAppsDomainVO();
			BeanUtils.copyProperties(domain, domainVO);
			if (domain.getGroupId() != null){
				MarketingConfigGroup group = groupMapper.selectById(domain.getGroupId());
				if (group != null)
					domainVO.setGroupName(group.getGroupName());
			}
			domainVOList.add(domainVO);
		}
		appsVO.setDomains(domainVOList);
		return appsVO;
	}

	/**
	 * 批量更新应用信息
	 * @param reqDtoList 批量更新参数
	 * @return Long
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public R batchUpdateMarketingApps(List<BatchUpdateMarketingAppsDTO> reqDtoList) {
		for (BatchUpdateMarketingAppsDTO reqDto : reqDtoList) {
			Long id = reqDto.getId();
			if (reqDto.getId() == null){
				throw new BusinessException("应用ID不能为空");
			}

			MarketingApps apps = appsMapper.selectById(id);
			if (apps == null){
				throw new BusinessException("应用ID:"+id+"不存在");
			}
			if (!apps.getStatus()){
				throw new BusinessException("应用ID:"+id+"已拉黑，请还原后操作");
			}

			// 1、更新基本信息
			MarketingApps marketingApps = new MarketingApps();
			BeanUtils.copyProperties(reqDto, marketingApps);
			appsMapper.updateById(marketingApps);


			// 2. 处理IP信息（包含分组检查）
			handleIpOperations(reqDto, id);

			// 3. 处理域名信息（包含分组检查）
			handleDomainOperations(reqDto, id);
		}
		return R.ok();
	}

	/**
	 * 设置应用信息
	 * @param reqDto 更新参数
	 * @return Long
	 */
	@Override
	public Boolean setMarketingAppsInfo(SetMarketingAppsDTO reqDto) {
		MarketingApps app = appsMapper.selectById(reqDto.getId());
		if (app == null){
			throw new BusinessException("应用不存在");
		}
		if (!app.getStatus()){
			throw new BusinessException("应用ID:"+app.getId()+"已拉黑，请还原后操作");
		}
		MarketingApps apps = new MarketingApps();
		BeanUtils.copyProperties(reqDto, apps);
		int i = appsMapper.updateById(apps);
		return i>0 ;
	}

	/**
	 * 设置应用状态
	 * @param reqDto 设置参数
	 * @return  Boolean
	 */
	@Override
	public Boolean setAppStatusById(SetMarketingAppsStatusDTO reqDto) {
		MarketingApps apps = appsMapper.selectById(reqDto.getId());
		if (apps == null) {
			throw new BusinessException("应用不存在");
		}
		apps.setStatus(reqDto.getStatus());
		return appsMapper.updateById(apps) > 0;
	}

	/**
	 * 同步应用列表
	 *
	 * @return 应用列表大小
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Map<String, Integer> syncedAppList() {
		List<MarketingApps> appList = getAppsFromLafaService();


		// 初始化统计结果
		Map<String, Integer> result = new HashMap<>();
		int addCount = 0;
		int updateCount = 0;
		int deleteCount = 0;

		// 1. 获取lafa服务应用的appId集合
		Set<String> lafaAppIds = appList.stream()
				.map(MarketingApps::getAppId)
				.collect(Collectors.toSet());

		// 2. 查询本地数据库中所有未删除的应用
		List<MarketingApps> localApps = appsMapper.selectList(new QueryWrapper<>());

		// 3. 将本地应用按appId分组，便于快速查询
		Map<String, MarketingApps> localAppMap = localApps.stream()
				.collect(Collectors.toMap(MarketingApps::getAppId, app -> app));

		// 4. 获取全局配置
		AtomicReference<Integer> triggerRule = new AtomicReference<>();
		AtomicReference<String> triggerNum = new AtomicReference<>("");
		R<ArrayList<SysPublicParamDTO>> ParamDTO = remoteParamService.getParamList(Arrays.asList(TRIGGER_RULE, TRIGGER_NUM));

		ParamDTO.getData().forEach(param -> {
			if (TRIGGER_RULE.equals(param.getPublicKey())) {
				triggerRule.set(Integer.valueOf(param.getPublicValue()));
			} else if (TRIGGER_NUM.equals(param.getPublicKey())) {
				triggerNum.set(param.getPublicValue());
			}
		});

		// 5. 处理新增和更新
		for (MarketingApps app : appList) {
			MarketingApps localApp = localAppMap.get(app.getAppId());

			if (localApp == null) {
				// 4.1 本地不存在，新增
				app.setStatus( true);
				app.setDomainLimit(false);
				app.setLaunch( true);
				app.setTriggerRule(triggerRule.get());
				app.setTriggerNum(triggerNum.get());
				appsMapper.insert(app);
				addCount++;
			} else {
				// 4.2 本地存在，判断是否需要更新
				// 复制ID（本地自增ID）和创建时间（保留原始创建时间）
				app.setId(localApp.getId());

				// 对比是否有变化
				if (!isSameApp(app, localApp)) {
					appsMapper.updateById(app);
					updateCount++;
				}
			}
		}

		// 5. 处理删除：本地存在但A服务不存在的应用，标记为删除
		for (MarketingApps localApp : localApps) {
			if (!lafaAppIds.contains(localApp.getAppId())) {
				appsMapper.deleteById(localApp);
				// 删除应用关联的IP、域名
				appsIpMapper.delete(Wrappers.<MarketingAppsIp>lambdaQuery().eq(MarketingAppsIp::getAppId, localApp.getId()));
				appsDomainMapper.delete(Wrappers.<MarketingAppsDomain>lambdaQuery().eq(MarketingAppsDomain::getAppId, localApp.getId()));
				deleteCount++;
			}
		}

		// 6. 组装结果
		result.put("add", addCount);
		result.put("update", updateCount);
		result.put("delete", deleteCount);
		return result;
	}

	/**
	 * 修改应用IP列表
	 * @param reqDto 修改参数
	 * @return R
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public R modMarketingAppsIps(ModMarketingAppsIpDTO reqDto) {
		Long appId = reqDto.getId();
		if (reqDto.getId() == null) {
			throw new BusinessException("应用ID不能为空");
		}
		MarketingApps app = appsMapper.selectById(appId);
		if (app == null){
			throw new BusinessException("应用ID:"+appId+"不存在");
		}
		if (!app.getStatus()){
			throw new BusinessException("应用ID:"+app.getId()+"已拉黑，请还原后操作");
		}
		BatchUpdateMarketingAppsDTO updateIp = new BatchUpdateMarketingAppsDTO();
		updateIp.setId(appId);
		updateIp.setIps(reqDto.getIps());
		updateIp.setDelIps(reqDto.getDelIps());
		// 处理IP信息
		handleIpOperations(updateIp, appId);
		return  R.ok();
	}

	/**
	 * 修改应用域名列表
	 * @param reqDto 修改参数
	 * @return R
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public R modMarketingAppsDomains(ModMarketingAppsDomainDTO reqDto) {
		Long appId = reqDto.getId();
		if (reqDto.getId() == null){
			throw new BusinessException("应用ID不能为空");
		}
		MarketingApps app = appsMapper.selectById(appId);
		if (app == null){
			throw new BusinessException("应用ID:"+appId+"不存在");
		}
		if (!app.getStatus()){
			throw new BusinessException("应用ID:"+app.getId()+"已拉黑，请还原后操作");
		}
		BatchUpdateMarketingAppsDTO updateDomain = new BatchUpdateMarketingAppsDTO();
		updateDomain.setId(appId);
		updateDomain.setDomains(reqDto.getDomains());
		updateDomain.setDelDomains(reqDto.getDelDomains());
		// 处理域名信息
		handleDomainOperations(updateDomain, appId);
		return R.ok();
	}

	/**
	 * 分页统计应用一级营销数据
	 * @param reqDto 查询参数
	 * @return 一级营销数据
	 */
	@Override
	public Page<PageStatAppFirstMktDataVO> pageStatAppFirstMktData(PageStatAppMktDataDTO reqDto) {
		Page<PageStatAppFirstMktDataVO> page = new Page<>(reqDto.getCurrent(), reqDto.getSize());

		LocalDateTime[] timeRange = reqDto.getTimeRange();
		LocalDateTime startTime = timeRange != null && timeRange.length > 0 ? timeRange[0] : null;
		LocalDateTime endTime = timeRange != null && timeRange.length > 1 ? timeRange[1] : null;

		List<PageStatAppFirstMktDataVO> records = appsMapper.statAppFirstMktData(page, reqDto.getAppId(), startTime, endTime);

		for (PageStatAppFirstMktDataVO record : records) {
			String ip = record.getIp();
			String region = IPUtils.getIpRegion(ip);
			record.setRegion(region);
		}
		page.setRecords(records);
		return page;
	}

	/**
	 * 分页统计应用二级营销数据
	 * @param reqDto 统计参数
	 * @return 二级营销数据
	 */
	@Override
	public Page<PageStatAppSecondMktDataVO> pageStatAppSecondMktData(PageStatAppMktDataDTO reqDto, String ip) {
		Page<PageStatAppSecondMktDataVO> page = new Page<>(reqDto.getCurrent(), reqDto.getSize());

		LocalDateTime[] timeRange = reqDto.getTimeRange();
		LocalDateTime startTime = timeRange != null && timeRange.length > 0 ? timeRange[0] : null;
		LocalDateTime endTime = timeRange != null && timeRange.length > 1 ? timeRange[1] : null;

		// 调用mapper查询，自动填充分页信息
		List<PageStatAppSecondMktDataVO> records = appsMapper.statAppSecondMktData(page, reqDto.getAppId(), ip, startTime, endTime);
		page.setRecords(records);
		return page;
	}

	/**
	 * 从lafa服务获取应用列表
	 * @return 应用列表
	 */
	public List<MarketingApps> getAppsFromLafaService(){

		// 构建请求参数
		JSONObject requestParam = new JSONObject();
		requestParam.put("accessKey", accessKey);
		// 创建OkHttp客户端
		OkHttpClient client = new OkHttpClient();

		// 构建POST请求体
		MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
		RequestBody body = RequestBody.create(mediaType, requestParam.toJSONString());

		// 构建请求
		Request request = new Request.Builder()
				.url(getAppListUrl)
				.post(body)
				.build();

		try {
			// 发送请求并获取响应
			Response response = client.newCall(request).execute();
			ArrayList<MarketingApps> appList = new ArrayList<>();
			if (response.isSuccessful() && response.body() != null) {
				JSONObject responseBody = JSONObject.parseObject(response.body().string());
				JSONArray apps = responseBody.getJSONArray("apps");
				apps.forEach(item -> {
					JSONObject app = (JSONObject) item;
					MarketingApps marketingApps = new MarketingApps();
					marketingApps.setAppId(app.getString("id"));
					marketingApps.setAppName(app.getString("name"));
					marketingApps.setAppImg(app.getString("img"));
					marketingApps.setAppUrl("https://"+app.getString("download_url")+"/"+marketingApps.getAppId());
					marketingApps.setBackupUrl("https://"+app.getString("backup_url")+"/"+marketingApps.getAppId());
					marketingApps.setDomainType(app.getInteger("type"));
					appList.add(marketingApps);
				});
				return appList;
			} else {
				// 响应失败
				log.error("请求失败,响应码: {}", response.code());
			}
			return null;
		} catch (IOException e) {
			// 网络请求异常
			log.error("网络请求异常: {}", e.getLocalizedMessage());
			return null;
		}
	}

	/**
	 * 对比两个应用是否相同
	 * @param newApp 新数据
	 * @param oldApp 旧数据
	 * @return 是否相同
	 */
	private boolean isSameApp(MarketingApps newApp, MarketingApps oldApp) {
		// 比较核心业务字段
		return Objects.equals(newApp.getAppId(), oldApp.getAppId()) &&
				Objects.equals(newApp.getAppName(), oldApp.getAppName()) &&
				Objects.equals(newApp.getAppImg(), oldApp.getAppImg()) &&
				Objects.equals(newApp.getAppUrl(), oldApp.getAppUrl()) &&
				Objects.equals(newApp.getBackupUrl(), oldApp.getBackupUrl()) &&
				Objects.equals(newApp.getDomainType(), oldApp.getDomainType());
	}

	/**
	 * 处理IP的新增/修改/删除，包含分组存在性检查
	 */
	private void handleIpOperations(BatchUpdateMarketingAppsDTO reqDto, Long appId) throws BusinessException {
		// 2.1 删除指定IP
		if (reqDto.getDelIps() != null && !reqDto.getDelIps().isEmpty()) {
			appsIpMapper.deleteByIds(reqDto.getDelIps());
		}

		// 2.2 新增或修改IP
		if (reqDto.getIps() != null && !reqDto.getIps().isEmpty()) {
			for (MarketingAppsIpDTO ipDto : reqDto.getIps()) {
				if (ipDto.getId() != null && (ipDto.getModify()==null || !ipDto.getModify())){
					continue;
				}
				// 去除无用数据
				if (ipDto.getSourceType() == 1){
					ipDto.setIpMode(null);
					ipDto.setStartIp(null);
					ipDto.setEndIp( null);

					// 查询分组是否存在
					MarketingConfigGroup group = groupMapper.selectOne(Wrappers.<MarketingConfigGroup>lambdaQuery()
							.eq(MarketingConfigGroup::getId, ipDto.getGroupId())
							.eq(MarketingConfigGroup::getGroupType, 1)
					);
					if (group == null){
						throw new BusinessException("分组ID:"+ipDto.getGroupId()+"不存在");
					}
				}else {
					ipDto.setGroupId(null);
					ipDto.setGroupName(null);
					if (ipDto.getIpMode() == 1){
						ipDto.setEndIp(null);
					}
				}

				// 查询ip表和ip分组表中是否存在
				if (checkIp(ipDto, appId, false)){
					if (ipDto.getSourceType() == 1){
						throw new BusinessException("分组ID:"+ipDto.getGroupId()+"已存在");
					}
					if (ipDto.getIpMode() == 1){
						throw new BusinessException("ip:"+ipDto.getStartIp()+"已存在");
					}
					String[] end = ipDto.getEndIp().split("\\.");
					throw new BusinessException("ip:"+ipDto.getStartIp()+"/"+end[3]+"已存在、或有重叠");
				}

				// 执行新增或修改
				MarketingAppsIp appsIp = new MarketingAppsIp();
				BeanUtils.copyProperties(ipDto, appsIp);
				appsIp.setAppId(appId);

				if (ipDto.getId() == null) {
					appsIp.setConfig(false);
					appsIpMapper.insert(appsIp);
				} else if (ipDto.getModify() != null && ipDto.getModify()) {
					appsIpMapper.updateById(appsIp);
				}
			}
		}
	}

	/**
	 * 处理域名的新增/修改/删除，包含完整校验逻辑
	 */
	private void handleDomainOperations(BatchUpdateMarketingAppsDTO reqDto, Long appId) throws BusinessException {
		// 3.1 删除指定域名
		if (reqDto.getDelDomains() != null && !reqDto.getDelDomains().isEmpty()) {
			appsDomainMapper.deleteBatchIds(reqDto.getDelDomains());
		}

		// 3.2 新增或修改域名
		if (reqDto.getDomains() != null && !reqDto.getDomains().isEmpty()) {
			for (MarketingAppsDomainDTO domainDto : reqDto.getDomains()) {
				if (domainDto.getId() != null && (domainDto.getModify()==null || !domainDto.getModify())){
					continue;
				}

				// 去除无用数据
				if (domainDto.getSourceType() == 1){
					domainDto.setDomain(null);

					// 查询分组是否存在
					MarketingConfigGroup group = groupMapper.selectOne(Wrappers.<MarketingConfigGroup>lambdaQuery()
							.eq(MarketingConfigGroup::getId, domainDto.getGroupId())
							.eq(MarketingConfigGroup::getGroupType, 2)
					);
					if (group == null){
						throw new BusinessException("分组ID:"+domainDto.getGroupId()+"不存在");
					}
				}else {
					domainDto.setGroupId(null);
					domainDto.setGroupName(null);
				}

				if (checkDomain(domainDto, appId, false)){
					if (domainDto.getSourceType() == 1){
						throw new BusinessException("分组ID:"+domainDto.getGroupId()+"已存在");
					}
					throw new BusinessException("域名:"+domainDto.getDomain()+"已存在");
				}

				// 执行新增或修改
				MarketingAppsDomain appsDomain = new MarketingAppsDomain();
				BeanUtils.copyProperties(domainDto, appsDomain);
				appsDomain.setAppId(appId);

				if (domainDto.getId() == null) {
					appsDomain.setConfig(false);
					appsDomainMapper.insert(appsDomain);
				} else if (domainDto.getModify() != null && domainDto.getModify()) {
					appsDomainMapper.updateById(appsDomain);
				}
			}
		}
	}

	/**
	 * 判断IP是否已存在（单IP或IP段）
	 * @param appId 应用数据ID
	 * @param ipDto IP
	 * @return 是否存在
	 */
	@Override
	public Boolean checkIp(MarketingAppsIpDTO ipDto, Long appId, Boolean isConfig) {
		List<Long> groupIds = getAppRelatedGroupIds(appId, true, isConfig);
		if (ipDto.getSourceType().equals(1)){
			return groupIds.contains(ipDto.getGroupId());
		}
		// 1. 检查应用IP表
		if (checkAppsIpExists(ipDto, appId, isConfig)) {
			return true;
		}

		// 2. 检查分组IP表（需要关联应用关联的分组）
		return checkGroupIpExists(ipDto, groupIds);
	}

	/**
	 * 判断域名是否已存在
	 * @param domainDTO 域名信息DTO
	 * @param appId 应用ID
	 * @return 是否存在
	 */
	public Boolean checkDomain(MarketingAppsDomainDTO domainDTO, Long appId, Boolean isConfig) {
		List<Long> groupIds = getAppRelatedGroupIds(appId, false, isConfig);  // 需要实现获取应用关联的分组ID列表
		if (domainDTO.getSourceType().equals(1)){
			// 来自分组
			return groupIds.contains(domainDTO.getGroupId());
		}

		// 1. 检查应用域名表
		LambdaQueryWrapper<MarketingAppsDomain> appsQuery = new LambdaQueryWrapper<>();
		appsQuery.eq(appId != null, MarketingAppsDomain::getAppId, appId)
				.eq(MarketingAppsDomain::getSourceType, 2)
				.eq(MarketingAppsDomain::getDomain, domainDTO.getDomain())
				.eq(MarketingAppsDomain::getConfig, isConfig);
		if (appsDomainMapper.selectCount(appsQuery) > 0) {
			return true;
		}

		// 2. 检查分组域名表（需要关联应用关联的分组）
		if (!groupIds.isEmpty()) {
			LambdaQueryWrapper<MarketingGroupDomain> groupQuery = new LambdaQueryWrapper<>();
			groupQuery.in(MarketingGroupDomain::getGroupId, groupIds)
					.eq(MarketingGroupDomain::getDomain, domainDTO.getDomain());
			return groupDomainMapper.selectCount(groupQuery) > 0;
		}
		return false;
	}

	/**
	 * 检查应用IP表中是否存在冲突
	 */
	private Boolean checkAppsIpExists(MarketingAppsIpDTO ipDto,Long appId, Boolean isConfig){
		// 1、校验该appId应用下ip表，及ip分组表中，是否存在该ip
		// 1.1、校验marketing_apps_ip表，appId=appId,是否包含
		// 1.2、校验marketing_group_ip表，是否包含ip，如果包含查出分组id,在查看appId下是否包含这个分组
		QueryWrapper<MarketingAppsIp> query = new QueryWrapper<>();
		query.eq("source_type",2).eq("config", isConfig?1:0);
		if (appId != null){
			query.eq("app_id", appId);
		}

		query.and(wrapper -> {
			// 单IP模式检查
			if (ipDto.getIpMode() == 1) {
				String targetIp = ipDto.getStartIp();
				// 检查是否有相同单IP
				wrapper.and(w -> w
						.eq("ip_mode", 1)
						.eq("start_ip", targetIp));

				// 检查是否被IP段包含
				wrapper.or(w -> w
						.eq("ip_mode", 2)
						.apply("INET_ATON({0}) BETWEEN INET_ATON(start_ip) AND INET_ATON(end_ip)", targetIp));

			}

			// IP段模式检查
			if (ipDto.getIpMode() == 2) {
				String startIp = ipDto.getStartIp();
				String endIp = ipDto.getEndIp();

				// 检查是否与单IP重叠：单IP在输入IP段范围内
				wrapper.and(w -> w
						.eq("ip_mode", 1)
						.apply("INET_ATON(start_ip) BETWEEN INET_ATON({0}) AND INET_ATON({1})", startIp, endIp));
				// 检查是否与IP段重叠：两个IP段有交集
				wrapper.or(w -> w
						.eq("ip_mode", 2)
						.and(w2 -> w2
								.apply("INET_ATON(start_ip) BETWEEN INET_ATON({0}) AND INET_ATON({1})", startIp, endIp)
								.or().apply("INET_ATON(end_ip) BETWEEN INET_ATON({0}) AND INET_ATON({1})", startIp, endIp)
								.or().apply("INET_ATON({0}) BETWEEN INET_ATON(start_ip) AND INET_ATON(end_ip)", startIp)
						)
				);
			}
		});
		return appsIpMapper.selectCount(query) > 0;
	}

	/**
	 * 检查分组IP表中是否存在冲突
	 */
	private boolean checkGroupIpExists(MarketingAppsIpDTO ipDTO, List<Long> groupIds) {
		if (groupIds.isEmpty()) {
			return false;
		}

		QueryWrapper<MarketingGroupIp> query = new QueryWrapper<>();
		query.in("group_id", groupIds);

		// 单IP模式
		if (ipDTO.getIpMode() == 1) {
			String targetIp = ipDTO.getStartIp();
			// 检查是否有相同单IP
			query.and(wrapper -> wrapper
					.eq("ip_mode", 1)
					.eq("start_ip", targetIp));

			// 检查是否被IP段包含
			query.or(wrapper -> wrapper
					.eq("ip_mode", 2)
					.apply("INET_ATON({0}) BETWEEN INET_ATON(start_ip) AND INET_ATON(end_ip)", targetIp));
		}

		// IP段模式检查
		if (ipDTO.getIpMode() == 2) {
			String startIp = ipDTO.getStartIp();
			String endIp = ipDTO.getEndIp();

			query.and(wrapper -> wrapper
					.eq("ip_mode", 1)
					.apply("INET_ATON(start_ip) BETWEEN INET_ATON({0}) AND INET_ATON({1})", startIp, endIp));

			query.or(wrapper -> wrapper
					.eq("ip_mode", 2)
					.and(w2 -> w2
							.apply("INET_ATON(start_ip) BETWEEN INET_ATON({0}) AND INET_ATON({1})", startIp, endIp)
							.or().apply("INET_ATON(end_ip) BETWEEN INET_ATON({0}) AND INET_ATON({1})", startIp, endIp)
							.or().apply("INET_ATON({0}) BETWEEN INET_ATON(start_ip) AND INET_ATON(end_ip)", startIp)
					)
			);
		}
		return groupIpMapper.selectCount(query) > 0;
	}

	/**
	 * 获取应用关联的所有分组ID
	 */
	private List<Long> getAppRelatedGroupIds(Long appId, Boolean isIp, Boolean isConfig) {
		// 示例实现，实际需根据业务调整
		if (isIp) {
			LambdaQueryWrapper<MarketingAppsIp> query = new LambdaQueryWrapper<>();
			query.eq(appId!=null ,MarketingAppsIp::getAppId, appId)
					.eq(MarketingAppsIp::getConfig, isConfig)
					.eq(MarketingAppsIp::getSourceType, 1)  // 来源类型为分组
					.select(MarketingAppsIp::getGroupId)
					.groupBy(MarketingAppsIp::getGroupId);
			return appsIpMapper.selectObjs(query).stream()
					.map(obj -> (Long) obj)
					.toList();
		}else {
			LambdaQueryWrapper<MarketingAppsDomain> query = new LambdaQueryWrapper<>();
			query.eq(appId!=null, MarketingAppsDomain::getAppId, appId)
					.eq(MarketingAppsDomain::getConfig, isConfig)
					.eq(MarketingAppsDomain::getSourceType, 1)  // 来源类型为分组
					.select(MarketingAppsDomain::getGroupId)
					.groupBy(MarketingAppsDomain::getGroupId);
			return appsDomainMapper.selectObjs(query).stream()
					.map(obj -> (Long) obj)
					.toList();
		}
	}


}
