/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the yifu4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */
package com.yifu.cloud.plus.v1.yifu.archives.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ArrayUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yifu.cloud.plus.v1.yifu.archives.entity.*;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.*;
import com.yifu.cloud.plus.v1.yifu.archives.service.TAutoMainRelService;
import com.yifu.cloud.plus.v1.yifu.archives.vo.*;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.ServiceNameConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.*;
import com.yifu.cloud.plus.v1.yifu.common.core.util.equator.HrEquator;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.YifuUser;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.ArchivesDaprUtil;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.SocialDaprUtils;
import com.yifu.cloud.plus.v1.yifu.common.security.util.SecurityUtils;
import com.yifu.cloud.plus.v1.yifu.insurances.vo.AutoDeptDetailVO;
import com.yifu.cloud.plus.v1.yifu.insurances.vo.AutoDeptVO;
import com.yifu.cloud.plus.v1.yifu.social.entity.SysBaseSetInfo;
import com.yifu.cloud.plus.v1.yifu.social.vo.SysBaseSetInfoVo;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static com.alibaba.fastjson.serializer.SerializerFeature.*;

/**
 * 项目配置表主表
 *
 * @author fxj
 * @date 2025-03-13 15:15:26
 */
@Log4j2
@Service
public class TAutoMainRelServiceImpl extends ServiceImpl<TAutoMainRelMapper, TAutoMainRel> implements TAutoMainRelService {

	@Autowired
	private TAutoEmpRuleInfoMapper autoEmpRuleInfoMapper;

	@Autowired
	private TAutoRuleLogMapper autoRuleLogMapper;

	@Autowired
	private SysAutoDictItemMapper autoDictItemMapper;

	@Autowired
	private ArchivesDaprUtil archivesDaprUtil;

	@Autowired
	private SysAutoDictMapper autoDictMapper;

	@Autowired
	private TAutoInsurRuleInfoMapper autoInsurRuleInfoMapper;

	@Autowired
	private TAutoInsurStandardMapper autoInsurStandardMapper;

	@Autowired
	private TAutoStandardInfoMapper autoStandardInfoMapper;

	@Autowired
	private TAutoContractRuleInfoMapper autoContractRuleInfoMapper;

	@Autowired
	private TAutoContractSchemeMapper contractSchemeMapper;
	
	// 社保规则主表Mapper
	@Autowired
	private TAutoSocialRuleInfoMapper autoSocialRuleInfoMapper;
	
	// 社保规则明细表Mapper
	@Autowired
	private TAutoSocialRuleRelMapper autoSocialRuleRelMapper;

	// 公积金规则主表Mapper
	@Autowired
	private TAutoFundRuleInfoMapper autoFundRuleInfoMapper;

	// 公积金规则明细表Mapper
	@Autowired
	private TAutoFundRuleRelMapper autoFundRuleRelMapper;

	@Autowired
	private SocialDaprUtils socialDaprUtils;

	public static final String itemsLabel = "label,description,disable";

	public static final String itemsLabelRepeat = "同一项目岗位名称不可重复";

	public static final String buyStandardRepeat = "'同一保险公司+险种+购买标准+购买地'或‘配置名称’不可重复";

	public static final String schemeNameRepeat = "配置名称不可重复";

    /**
     * 项目配置表主表简单分页查询
     * @param tAutoMainRel 项目配置表主表
     * @return
     */
    @Override
    public IPage<TAutoMainRel> getTAutoMainRelPage(Page<TAutoMainRel> page, TAutoMainRelSearchVo tAutoMainRel){
        return baseMapper.getTAutoMainRelPage(page,tAutoMainRel);
    }

    /**
     * 项目配置表主表批量导出
     * @param searchVo 项目配置表主表
     * @return
     */
    @Override
    public void listExport(HttpServletResponse response, TAutoMainRelSearchVo searchVo){
        String fileName = "项目配置表批量导出" + DateUtil.getThisTime() + ".xlsx";
        //获取要导出的列表
        List<TAutoMainRelExportVo> list = new ArrayList<>();
        long count = noPageCountDiy(searchVo);
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            response.setContentType(CommonConstants.MULTIPART_FORM_DATA);
            response.setCharacterEncoding("utf-8");
            response.setHeader(CommonConstants.CONTENT_DISPOSITION, CommonConstants.ATTACHMENT_FILENAME + URLEncoder.encode(fileName  , CommonConstants.UTF8));
            // 这里 需要指定写用哪个class去写，然后写到第一个sheet，然后文件流会自动关闭
            ExcelWriter  excelWriter = EasyExcel.write(out, TAutoMainRelExportVo.class).build();
            int index = 0;
            if (count >  CommonConstants.ZERO_INT){
                for (int i = 0; i <= count; ) {
                    // 获取实际记录
                    searchVo.setLimitStart(i);
                    searchVo.setLimitEnd(CommonConstants.EXCEL_EXPORT_LIMIT);
                    list = noPageDiy(searchVo);
                    if (Common.isNotNull(list)){
                        ExcelUtil<TAutoMainRelExportVo> util = new ExcelUtil<>(TAutoMainRelExportVo.class);
                        for (TAutoMainRelExportVo vo:list){
                            util.convertEntity(vo,null,null,null);
                        }
                    }
                    if (Common.isNotNull(list)){
                        WriteSheet writeSheet = EasyExcel.writerSheet("项目配置表主表"+index).build();
                        excelWriter.write(list,writeSheet);
                        index++;
                    }
                    i = i + CommonConstants.EXCEL_EXPORT_LIMIT;
                    if (Common.isNotNull(list)){
                        list.clear();
                    }
                }
            }else {
                WriteSheet writeSheet = EasyExcel.writerSheet("项目配置表主表"+index).build();
                excelWriter.write(list,writeSheet);
            }
            if (Common.isNotNull(list)){
                list.clear();
            }
            out.flush();
            excelWriter.finish();
        }catch (Exception e){
            log.error("执行异常" ,e);
        }finally {
            try {
                if (null != out) {
                    out.close();
                }
            } catch (IOException e) {
                log.error("执行异常", e);
            }
        }
    }

    @Override
    public List<TAutoMainRelExportVo> noPageDiy(TAutoMainRelSearchVo searchVo) {

        return baseMapper.noPageDiy(searchVo);
    }

	private  Long noPageCountDiy(TAutoMainRelSearchVo searchVo) {
        return baseMapper.noPageCountDiy(searchVo);
    }

    private LambdaQueryWrapper buildQueryWrapper(TAutoMainRelSearchVo entity){
        LambdaQueryWrapper<TAutoMainRel> wrapper = Wrappers.lambdaQuery();
        if (ArrayUtil.isNotEmpty(entity.getCreateTimes())) {
            wrapper.ge(TAutoMainRel::getCreateTime, entity.getCreateTimes()[0])
                    .le(TAutoMainRel::getCreateTime,
                            entity.getCreateTimes()[1]);
        }
        if (Common.isNotNull(entity.getCreateName())){
            wrapper.eq(TAutoMainRel::getCreateName,entity.getCreateName());
        }
        return wrapper;
    }

    @Override
    public R<List<ErrorMessage>> importDiy(InputStream inputStream) {
        return  R.ok();
    }
    private void importTAutoMainRel(List<TAutoMainRelVo> excelVOList, List<ErrorMessage> errorMessageList) {
        // 个性化校验逻辑
        ErrorMessage errorMsg;
        // 执行数据插入操作 组装
        for (int i = 0; i < excelVOList.size(); i++) {
            TAutoMainRelVo excel = excelVOList.get(i);
            // 数据合法情况 TODO

            // 插入
            insertExcel(excel);
            errorMessageList.add(new ErrorMessage(excel.getRowIndex(),CommonConstants.SAVE_SUCCESS));
        }
    }
    /**
     * 插入excel bad record
     */
    private void insertExcel(TAutoMainRelVo excel) {
        TAutoMainRel insert = new TAutoMainRel();
        BeanUtil.copyProperties(excel, insert);
        this.save(insert);
    }

	@Override
	public R<TAutoMainRelDetailVo> getByIdAsso(String id) {
		TAutoMainRelDetailVo detailVo = new TAutoMainRelDetailVo();
		//项目配置主表
		TAutoMainRel mainRel = baseMapper.selectById(id);
		if (Common.isEmpty(mainRel)){
			return R.failed(CommonConstants.PARAM_IS_NOT_ERROR);
		}
		detailVo.setAutoMainRel(mainRel);
		//档案管理规则配置表
		detailVo.setAutoEmpRuleInfo(autoEmpRuleInfoMapper.selectOne(Wrappers.<TAutoEmpRuleInfo>query().lambda()
				.eq(TAutoEmpRuleInfo::getMainId,id).last(CommonConstants.LAST_ONE_SQL)));
		//项目配置日志表
		detailVo.setAutoRuleLogs(autoRuleLogMapper.selectList(Wrappers.<TAutoRuleLog>query().lambda()
				.eq(TAutoRuleLog::getMainId,id)));
		//岗位信息表
		detailVo.setAutoDictItems(autoDictItemMapper.selectList(Wrappers.<SysAutoDictItem>query().lambda()
				.eq(SysAutoDictItem::getDeptNo,mainRel.getDeptNo())
				.eq(SysAutoDictItem::getDisable,CommonConstants.ZERO_STRING)));
		//项目信息表
		detailVo.setSettleDomainVo(archivesDaprUtil.selectDeptByNo(mainRel.getDeptNo()));
		//商险规则表
		detailVo.setAutoInsurRuleInfo(autoInsurRuleInfoMapper.selectOne(Wrappers.<TAutoInsurRuleInfo>query().lambda()
				.eq(TAutoInsurRuleInfo::getMainId,id).last(CommonConstants.LAST_ONE_SQL)));
		//商险标准表
		if (Common.isNotNull(detailVo.getAutoInsurRuleInfo())){
			List<TAutoInsurStandard> standards = autoInsurStandardMapper.selectList(Wrappers.<TAutoInsurStandard>query()
					.lambda().eq(TAutoInsurStandard::getMainId, detailVo.getAutoInsurRuleInfo().getId()));
			if (Common.isNotNull(standards)){
				for (TAutoInsurStandard standard : standards) {
					standard.setStandardInfos(autoStandardInfoMapper.selectList(Wrappers.<TAutoStandardInfo>query()
							.lambda().eq(TAutoStandardInfo::getMainId,standard.getId())));
				}
			}
			detailVo.setAutoInsurStandards(standards);
		}
		//员工合同签订规则配置表
		detailVo.setContractRuleInfo(autoContractRuleInfoMapper.selectOne(Wrappers.<TAutoContractRuleInfo>query().lambda()
				.eq(TAutoContractRuleInfo::getMainId,id).last(CommonConstants.LAST_ONE_SQL)));
		//员工合同签订规则配置方案表
		if (Common.isNotNull(detailVo.getContractRuleInfo())){
			detailVo.setContractSchemes(contractSchemeMapper.selectList(Wrappers.<TAutoContractScheme>query().lambda()
					.eq(TAutoContractScheme::getDeptId,mainRel.getDeptId())));
		}
		//社保规则配置表
		detailVo.setSocialRuleInfo(autoSocialRuleInfoMapper.selectOne(Wrappers.<TAutoSocialRuleInfo>query().lambda()
				.eq(TAutoSocialRuleInfo::getMainId,id)));
		//社保规则配置明细表
		detailVo.setSocialRuleRels(autoSocialRuleRelMapper.selectList(Wrappers.<TAutoSocialRuleRel>query().lambda()
				.eq(TAutoSocialRuleRel::getDeptId,mainRel.getDeptId())));
		//公积金规则配置表
		detailVo.setFundRuleInfo(autoFundRuleInfoMapper.selectOne(Wrappers.<TAutoFundRuleInfo>query().lambda()
				.eq(TAutoFundRuleInfo::getMainId,id)));
		//公积金规则配置明细表
		detailVo.setFundRuleRels(autoFundRuleRelMapper.selectList(Wrappers.<TAutoFundRuleRel>query().lambda()
				.eq(TAutoFundRuleRel::getDeptId,mainRel.getDeptId())));
		return R.ok(detailVo);
	}
	/**
	 * @Author fxj
	 * @Description 规则保存
	 * @Date 10:24 2025/3/14
	**/
	@Override
	@Transactional
	public R<Boolean> saveAsso(TAutoMainRelAddVo entity) {
		// 校验用户信息
		YifuUser user  = SecurityUtils.getUser();
		if (Common.isEmpty(user)){
			return R.failed(CommonConstants.USER_FAIL);
		}
		// 校验入参
		if (Common.isEmpty(entity) || Common.isEmpty(entity.getAutoMainRel())) {
			return R.failed(CommonConstants.PARAM_IS_NOT_ERROR);
		}

		TAutoMainRel autoMainRel = entity.getAutoMainRel();
		if (Common.isEmpty(autoMainRel.getDeptId()) || Common.isEmpty(autoMainRel.getDeptNo())) {
			return R.failed(CommonConstants.PARAM_IS_NOT_ERROR);
		}
		try {
			// 校验是否存在重复规则配置
			TAutoMainRel existRel = baseMapper.selectOne(Wrappers.<TAutoMainRel>query().lambda()
					.eq(TAutoMainRel::getDeptNo,autoMainRel.getDeptNo()).last(CommonConstants.LAST_ONE_SQL));
			if (!Common.isEmpty(existRel)){
				return R.failed("已存在对应项目规则配置！");
			}
			// 获取岗位字典
			SysAutoDict autoDict = autoDictMapper.selectOne(Wrappers.<SysAutoDict>query().lambda()
					.eq(SysAutoDict::getType,CommonConstants.POST_TYPE).last(CommonConstants.LAST_ONE_SQL));
			if (Common.isEmpty(autoDict)){
				return R.failed(CommonConstants.INIT_DATA_GET_FAIL);
			}
			// 校验员工规则信息
			TAutoEmpRuleInfo autoEmpRuleInfo = entity.getAutoEmpRuleInfo();
			if (Common.isNotNull(autoEmpRuleInfo)){
				ExcelUtil<TAutoEmpRuleInfo> excelUtil = new ExcelUtil<>(TAutoEmpRuleInfo.class);
				ErrorMessage errorMessage =  excelUtil.checkEntity(autoEmpRuleInfo,0);
				if (Common.isNotNull(errorMessage)){
					return R.failed(errorMessage.getMessage());
				}
			}
			//校验商险规则信息
			TAutoInsurRuleInfo autoInsurRuleInfo = entity.getAutoInsurRuleInfo();
			if (Common.isNotNull(autoInsurRuleInfo)){
				ExcelUtil<TAutoInsurRuleInfo> excelUtil = new ExcelUtil<>(TAutoInsurRuleInfo.class);
				ErrorMessage errorMessage =  excelUtil.checkEntity(autoInsurRuleInfo,0);
				if (Common.isNotNull(errorMessage)){
					return R.failed(errorMessage.getMessage());
				}
			}
			//校验商险购买标准
			List<TAutoInsurStandard> insurStandards = entity.getInsurStandards();
			R<Boolean> PARAM_IS_NOT_ERROR = checkInsurStandard(insurStandards);
			if (PARAM_IS_NOT_ERROR != null){
				return PARAM_IS_NOT_ERROR;
			}
			// 校验字典项是否有重复标签
			List<SysAutoDictItem> autoDictItems = entity.getAutoDictItems();
			if (!checkDictItemsForDuplicates(autoDictItems)) {
				return R.failed(itemsLabelRepeat);
			}
			//校验员工合同签订规则配置信息
			TAutoContractRuleInfo autoContractRuleInfo = entity.getContractRuleInfo();
			if (Common.isNotNull(autoContractRuleInfo)){
				ExcelUtil<TAutoContractRuleInfo> excelUtil = new ExcelUtil<>(TAutoContractRuleInfo.class);
				ErrorMessage errorMessage =  excelUtil.checkEntity(autoContractRuleInfo,0);
				if (Common.isNotNull(errorMessage)){
					return R.failed(errorMessage.getMessage());
				}
			}
			//校验员工合同签订规则配置方案信息
			List<TAutoContractScheme> contractSchemes = entity.getContractSchemes();
			PARAM_IS_NOT_ERROR = checkContractSchemes(contractSchemes);
			if (PARAM_IS_NOT_ERROR != null){
				return PARAM_IS_NOT_ERROR;
			}
			//校验社保规则主表信息
			TAutoSocialRuleInfo autoSocialRuleInfo = entity.getSocialRuleInfo();
			if (Common.isNotNull(autoSocialRuleInfo)){
				ExcelUtil<TAutoSocialRuleInfo> excelUtil = new ExcelUtil<>(TAutoSocialRuleInfo.class);
				ErrorMessage errorMessage =  excelUtil.checkEntity(autoSocialRuleInfo,0);
				if (Common.isNotNull(errorMessage)){
					return R.failed(errorMessage.getMessage());
				}
			}
			//校验社保规则明细表信息
			List<TAutoSocialRuleRel> socialRuleRels = entity.getSocialRuleRels();
			PARAM_IS_NOT_ERROR = checkSocialRuleRels(socialRuleRels);
			if (PARAM_IS_NOT_ERROR != null){
				return PARAM_IS_NOT_ERROR;
			}
			
			//校验公积金规则主表信息
			TAutoFundRuleInfo autoFundRuleInfo = entity.getFundRuleInfo();
			if (Common.isNotNull(autoFundRuleInfo)){
				ExcelUtil<TAutoFundRuleInfo> excelUtil = new ExcelUtil<>(TAutoFundRuleInfo.class);
				ErrorMessage errorMessage =  excelUtil.checkEntity(autoFundRuleInfo,0);
				if (Common.isNotNull(errorMessage)){
					return R.failed(errorMessage.getMessage());
				}
			}
			//校验公积金规则明细表信息
			List<TAutoFundRuleRel> fundRuleRels = entity.getFundRuleRels();
			PARAM_IS_NOT_ERROR = checkFundRuleRels(fundRuleRels);
			if (PARAM_IS_NOT_ERROR != null){
				return PARAM_IS_NOT_ERROR;
			}
			
			//新增主表
			autoMainRel.setRuleUpdatePerson(user.getNickname());
			autoMainRel.setRuleUpdateTime(DateUtil.getCurrentDateTime());
			int res = baseMapper.insert(autoMainRel);
			if (res <= CommonConstants.ZERO_INT){
				return R.failed(CommonConstants.SAVE_FAILED);
			}
			// 新增字典项
			if (Common.isNotNull(autoDictItems)) {
				for (SysAutoDictItem sysAutoDictItem:autoDictItems){
					//初始化字典信息
					initDictItem(sysAutoDictItem, user, autoDict, autoMainRel);
					sysAutoDictItem.setCreateTime(LocalDateTime.now());
					sysAutoDictItem.setCreateBy(user.getId());
					sysAutoDictItem.setCreateName(user.getNickname());
					autoDictItemMapper.insert(sysAutoDictItem);
				}
			}
			//新增档案规则
			if (Common.isNotNull(autoEmpRuleInfo)){
				autoEmpRuleInfo.setDeptNo(autoMainRel.getDeptNo());
				autoEmpRuleInfo.setDeptId(autoMainRel.getDeptId());
				autoEmpRuleInfo.setMainId(autoMainRel.getId());
				autoEmpRuleInfoMapper.insert(autoEmpRuleInfo);
			}
			//新增商险规则
			if (Common.isNotNull(autoInsurRuleInfo)){
				autoInsurRuleInfo.setDeptNo(autoMainRel.getDeptNo());
				autoInsurRuleInfo.setDeptId(autoMainRel.getDeptId());
				autoInsurRuleInfo.setMainId(autoMainRel.getId());
				autoInsurRuleInfoMapper.insert(autoInsurRuleInfo);
			}
			//新增商险购买标准
			if (Common.isNotNull(insurStandards)){
				for (TAutoInsurStandard standard:insurStandards){
					standard.setMainId(autoInsurRuleInfo.getId());
					autoInsurStandardMapper.insert(standard);
					//新增购买标准子表
					saveStandard(standard);
				}
			}
			//新增员工合同签订规则配置表
			if (Common.isNotNull(autoContractRuleInfo)){
				autoContractRuleInfo.setDeptNo(autoMainRel.getDeptNo());
				autoContractRuleInfo.setDeptId(autoMainRel.getDeptId());
				autoContractRuleInfo.setMainId(autoMainRel.getId());
				autoContractRuleInfoMapper.insert(autoContractRuleInfo);
			}
			//新增员工合同签订规则配置方案子表
			if (Common.isNotNull(contractSchemes)){
				for (TAutoContractScheme scheme:contractSchemes){
					scheme.setMainId(autoContractRuleInfo.getId());
					scheme.setDeptNo(autoMainRel.getDeptNo());
					scheme.setDeptId(autoMainRel.getDeptId());
					contractSchemeMapper.insert(scheme);
				}
			}
			//新增社保规则主表
			if (Common.isNotNull(autoSocialRuleInfo)){
				autoSocialRuleInfo.setDeptNo(autoMainRel.getDeptNo());
				autoSocialRuleInfo.setDeptId(autoMainRel.getDeptId());
				autoSocialRuleInfo.setMainId(autoMainRel.getId());
				autoSocialRuleInfo.setCreateBy(user.getId());
				autoSocialRuleInfo.setCreateTime(LocalDateTime.now());
				autoSocialRuleInfo.setCreateName(user.getNickname());
				autoSocialRuleInfoMapper.insert(autoSocialRuleInfo);
			}
			//新增社保规则明细表
			if (Common.isNotNull(socialRuleRels)){
				for (TAutoSocialRuleRel rel:socialRuleRels){
					rel.setMainId(autoSocialRuleInfo.getId());
					rel.setDeptNo(autoMainRel.getDeptNo());
					rel.setDeptId(autoMainRel.getDeptId());
					rel.setCreateBy(user.getId());
					rel.setCreateTime(LocalDateTime.now());
					rel.setCreateName(user.getNickname());
					autoSocialRuleRelMapper.insert(rel);
				}
			}
			//新增公积金规则主表
			if (Common.isNotNull(autoFundRuleInfo)){
				autoFundRuleInfo.setDeptNo(autoMainRel.getDeptNo());
				autoFundRuleInfo.setDeptId(autoMainRel.getDeptId());
				autoFundRuleInfo.setMainId(autoMainRel.getId());
				autoFundRuleInfo.setCreateBy(user.getId());
				autoFundRuleInfo.setCreateTime(LocalDateTime.now());
				autoFundRuleInfo.setCreateName(user.getNickname());
				autoFundRuleInfoMapper.insert(autoFundRuleInfo);
			}
			//新增公积金规则明细表
			if (Common.isNotNull(fundRuleRels)){
				for (TAutoFundRuleRel rel:fundRuleRels){
					rel.setMainId(autoFundRuleInfo.getId());
					rel.setDeptNo(autoMainRel.getDeptNo());
					rel.setDeptId(autoMainRel.getDeptId());
					rel.setCreateBy(user.getId());
					rel.setCreateTime(LocalDateTime.now());
					rel.setCreateName(user.getNickname());
					autoFundRuleRelMapper.insert(rel);
				}
			}
			return R.ok();
		}catch (Exception e){
			// 捕获异常并返回友好提示
			return R.failed("系统异常：" + e.getMessage());
		}
	}

	/**
	 * @Author fxj
	 * @Description 校验商险规则
	 * @Date 10:24 2025/6/11
	**/
	private R<Boolean> checkInsurStandard(List<TAutoInsurStandard> insurStandards) {
		if (Common.isNotNull(insurStandards)){
			List<TAutoStandardInfo> standards;
			ExcelUtil<TAutoInsurStandard> excelUtil = new ExcelUtil<>(TAutoInsurStandard.class);
			ErrorMessage errorMessage;
			for (TAutoInsurStandard standard: insurStandards){
				standards = standard.getStandardInfos();
				if (Common.isEmpty(standards)){
					return R.failed(CommonConstants.PARAM_IS_NOT_ERROR);
				}else {
					// 按字段 standard 排序后逗号拼接并去除末尾逗号
					standard.setStandard(standards.stream()
							.sorted(Comparator.comparing(TAutoStandardInfo::getStandard))
							.map(TAutoStandardInfo::getStandard)
							.collect(Collectors.joining(","))
							.replaceAll(",$",""));
				}

				errorMessage =  excelUtil.checkEntity(standard,0);
				if (Common.isNotNull(errorMessage)){
					return R.failed(errorMessage.getMessage());
				}
			}
			if (checkInsurStandardsForDuplicates(insurStandards)){
				return R.failed(buyStandardRepeat);
			}
		}
		return null;
	}
	/**
	 * @Author fxj
	 * @Description 校验合同规则
	 * @Date 10:24 2025/6/11
	**/
	private R<Boolean> checkContractSchemes(List<TAutoContractScheme> contractSchemes) {
		if (Common.isNotNull(contractSchemes)){
			ExcelUtil<TAutoContractScheme> excelUtil = new ExcelUtil<>(TAutoContractScheme.class);
			ErrorMessage errorMessage;
			for (TAutoContractScheme scheme: contractSchemes){
				errorMessage =  excelUtil.checkEntity(scheme,0);
				if (Common.isNotNull(errorMessage)){
					return R.failed(errorMessage.getMessage());
				}
			}
			if (checkContractSchemeForDuplicates(contractSchemes)){
				return R.failed(schemeNameRepeat);
			}
		}
		return null;
	}

	private boolean checkInsurStandardsForDuplicates(List<TAutoInsurStandard> insurStandards) {
		boolean result = false;
		if (Common.isNotNull(insurStandards)) {
			Map<String, String> map = new HashMap<>();
			for (TAutoInsurStandard standard : insurStandards) {
				if (map.put(standard.getCompany() + standard.getRiskType() + standard.getStandard(), "") != null) {
					result = true;
					break;
				}
				if (map.put(standard.getName(), "") != null) {
					result = true;
					break;
				}
			}
			map.clear();
		}
		return result;
	}
	//验证配置名称重复
	private boolean checkContractSchemeForDuplicates(List<TAutoContractScheme> schemes) {
		boolean result = false;
		if (Common.isNotNull(schemes)) {
			Map<String, String> map = new HashMap<>();
			for (TAutoContractScheme scheme : schemes) {
				if (map.put(scheme.getConfigName(), "") != null) {
					result = true;
					break;
				}
			}
			map.clear();
		}
		return result;
	}
	/**
	 * 检查字典项是否有重复标签
	 */
	private boolean checkDictItemsForDuplicates(List<SysAutoDictItem> autoDictItems) {
		Set<String> repeatItems = new HashSet<>();
		for (SysAutoDictItem item : autoDictItems) {
			if (Common.isEmpty(item.getLabel())) {
				return true; // 标签为空视为无效
			}
			if (!repeatItems.add(item.getLabel())) {
				return false; // 标签重复
			}
		}
		return true;
	}
	/**
	 * @Author fxj
	 * @Description 规则修改
	 * @Date 10:24 2025/3/14
	**/
	@Override
	/**
	 * 更新关联信息方法
	 *
	 * @param entity 包含要更新的关联信息的实体对象
	 * @return 返回一个表示操作结果的响应对象
	 */
	@Transactional
	public R<Boolean> updateAsso(TAutoMainRelAddVo entity) {
	    // 获取当前用户信息
	    YifuUser user  = SecurityUtils.getUser();
	    // 如果用户信息为空，则返回用户获取失败的响应
	    if (Common.isEmpty(user)){
	        return R.failed(CommonConstants.USER_FAIL);
	    }
	    // 如果传入的实体对象为空，则返回参数错误的响应
	    if (Common.isEmpty(entity)){
	        return R.failed(CommonConstants.PARAM_IS_NOT_ERROR);
	    }
	    // 获取实体对象中的关联信息
	    TAutoMainRel autoMainRel = entity.getAutoMainRel();
	    // 如果关联信息或其ID为空，则返回参数错误的响应
	    if (Common.isEmpty(autoMainRel) || Common.isEmpty(autoMainRel.getId())){
	        return R.failed(CommonConstants.PARAM_IS_NOT_ERROR);
	    }
	    // 根据ID查询原有的关联信息
	    TAutoMainRel autoMainRelOld = baseMapper.selectById(autoMainRel.getId());
	    // 如果查询结果为空，则返回参数错误的响应
	    if (!Common.isNotNull(autoMainRelOld)){
	        return   R.failed(CommonConstants.PARAM_IS_NOT_ERROR);
	    }
	    // 查询岗位字典信息
	    SysAutoDict autoDict = autoDictMapper.selectOne(Wrappers.<SysAutoDict>query().lambda()
	            .eq(SysAutoDict::getType,CommonConstants.POST_TYPE).last(CommonConstants.LAST_ONE_SQL));
	    // 如果岗位字典信息为空，则返回数据初始化失败的响应
	    if (Common.isEmpty(autoDict)){
	        return R.failed(CommonConstants.INIT_DATA_GET_FAIL);
	    }
	    // 获取实体对象中的员工规则信息
	    TAutoEmpRuleInfo autoEmpRuleNew = entity.getAutoEmpRuleInfo();
	    TAutoEmpRuleInfo autoEmpRuleOld = null;
	    // 如果员工规则信息不为空
	    if (Common.isNotNull(autoEmpRuleNew)){
	        // 如果员工规则信息的ID为空，则返回参数错误的响应
	        if (!Common.isNotNull(autoEmpRuleNew.getId())){
	            return R.failed(CommonConstants.PARAM_IS_NOT_ERROR);
	        }
	        // 根据ID查询原有的员工规则信息
	        autoEmpRuleOld = autoEmpRuleInfoMapper.selectById(autoEmpRuleNew.getId());
	        // 创建Excel工具对象
	        ExcelUtil<TAutoEmpRuleInfo> excelUtil = new ExcelUtil<>(TAutoEmpRuleInfo.class);
	        // 检查员工规则信息的有效性
	        ErrorMessage errorMessage =  excelUtil.checkEntity(autoEmpRuleNew,0);
	        // 如果检查结果不为空，则返回检查错误信息的响应
	        if (Common.isNotNull(errorMessage)){
	            return R.failed(errorMessage.getMessage());
	        }
	    }
		//校验商险规则信息
		TAutoInsurRuleInfo autoInsurRuleNew = entity.getAutoInsurRuleInfo();
		TAutoInsurRuleInfo autoInsurRuleOld = null;
		if (Common.isNotNull(autoInsurRuleNew)){
			// 检查商险规则信息的有效性
			ExcelUtil<TAutoInsurRuleInfo> excelUtil = new ExcelUtil<>(TAutoInsurRuleInfo.class);
			ErrorMessage errorMessage =  excelUtil.checkEntity(autoInsurRuleNew,0);
			if (Common.isNotNull(errorMessage)){
				return R.failed(errorMessage.getMessage());
			}
			// 根据ID查询原有的商险规则信息
			autoInsurRuleOld = autoInsurRuleInfoMapper.selectOne(Wrappers.<TAutoInsurRuleInfo>query().lambda()
					.eq(TAutoInsurRuleInfo::getMainId,autoMainRel.getId()).last(CommonConstants.LAST_ONE_SQL));
		}
		//商险购买标准是否更新标识  false 未更新  true 更新
		boolean flag = false;
		List<TAutoInsurStandard> insurStandardsOld = null;
		//校验商险购买标准
		List<TAutoInsurStandard>  insurStandards = entity.getInsurStandards();
		R<Boolean> PARAM_IS_NOT_ERROR = checkInsurStandard(insurStandards);
		if (PARAM_IS_NOT_ERROR != null){
			return PARAM_IS_NOT_ERROR;
		}
		if (checkInsurStandardsForDuplicates(insurStandards)){
			return R.failed(buyStandardRepeat);
		}
		// 更新岗位字典
		List<SysAutoDictItem> autoDictItems = entity.getAutoDictItems();
		Map<String,SysAutoDictItem> repeatItems = new HashMap<>();
		// 更新岗位字典
		List<SysAutoDictItem> oldAutoDictItems = autoDictItemMapper.selectList(Wrappers.<SysAutoDictItem>query()
				.lambda().eq(SysAutoDictItem::getDeptNo,autoMainRel.getDeptNo())
				.eq(SysAutoDictItem::getDisable,CommonConstants.ZERO_STRING));

		// 如果查询到旧的岗位字典项
		repeatItems = getStringSysAutoDictItemMap(autoDictItems, repeatItems, oldAutoDictItems);
		// 检验岗位字典是否重复
		R<Boolean> checkRes = checkItemRepeat(autoDictItems, repeatItems);
		// 如果检验结果不为空，则返回检验结果
		if (checkRes != null){
			return checkRes;
		}
		//校验员工合同签订规则主表和明细表
		TAutoContractRuleInfo autoContractRuleNew = entity.getContractRuleInfo();
		TAutoContractRuleInfo autoContractRuleOld = null;
		if (Common.isNotNull(autoContractRuleNew)){
			// 检查员工合同签订规则信息的有效性
			ExcelUtil<TAutoContractRuleInfo> excelUtil = new ExcelUtil<>(TAutoContractRuleInfo.class);
			ErrorMessage errorMessage =  excelUtil.checkEntity(autoContractRuleNew,0);
			if (Common.isNotNull(errorMessage)){
				return R.failed(errorMessage.getMessage());
			}
			// 根据ID查询原有的员工合同签订规则规则信息
			autoContractRuleOld = autoContractRuleInfoMapper.selectOne(Wrappers.<TAutoContractRuleInfo>query().lambda()
					.eq(TAutoContractRuleInfo::getMainId,autoMainRel.getId()).last(CommonConstants.LAST_ONE_SQL));
		}
		//员工合同签订规则方案配置是否更新标识  false 未更新  true 更新
		boolean schemeFlag = false;
		List<TAutoContractScheme> schemesOld = null;
		//员工合同签订规则方案配置
		List<TAutoContractScheme>  schemes = entity.getContractSchemes();
		PARAM_IS_NOT_ERROR = checkContractSchemes(schemes);
		if (PARAM_IS_NOT_ERROR != null){
			return PARAM_IS_NOT_ERROR;
		}
		//配置名称是否重复
		if (checkContractSchemeForDuplicates(schemes)){
			return R.failed(schemeNameRepeat);
		}
		
		//校验社保规则主表信息
		TAutoSocialRuleInfo autoSocialRuleNew = entity.getSocialRuleInfo();
		TAutoSocialRuleInfo autoSocialRuleOld = null;
		if (Common.isNotNull(autoSocialRuleNew)){
			// 检查社保规则信息的有效性
			ExcelUtil<TAutoSocialRuleInfo> excelUtil = new ExcelUtil<>(TAutoSocialRuleInfo.class);
			ErrorMessage errorMessage =  excelUtil.checkEntity(autoSocialRuleNew,0);
			if (Common.isNotNull(errorMessage)){
				return R.failed(errorMessage.getMessage());
			}
			// 根据ID查询原有的社保规则信息
			autoSocialRuleOld = autoSocialRuleInfoMapper.selectOne(Wrappers.<TAutoSocialRuleInfo>query().lambda()
					.eq(TAutoSocialRuleInfo::getMainId,autoMainRel.getId()).last(CommonConstants.LAST_ONE_SQL));
		}
		
		//社保规则明细是否更新标识  false 未更新  true 更新
		boolean socialFlag = false;
		List<TAutoSocialRuleRel> socialRuleRelsOld = null;
		//校验社保规则明细
		List<TAutoSocialRuleRel>  socialRuleRels = entity.getSocialRuleRels();
		PARAM_IS_NOT_ERROR = checkSocialRuleRels(socialRuleRels);
		if (PARAM_IS_NOT_ERROR != null){
			return PARAM_IS_NOT_ERROR;
		}
		
		//校验公积金规则主表信息
		TAutoFundRuleInfo autoFundRuleNew = entity.getFundRuleInfo();
		TAutoFundRuleInfo autoFundRuleOld = null;
		if (Common.isNotNull(autoFundRuleNew)){
			// 检查公积金规则信息的有效性
			ExcelUtil<TAutoFundRuleInfo> excelUtil = new ExcelUtil<>(TAutoFundRuleInfo.class);
			ErrorMessage errorMessage =  excelUtil.checkEntity(autoFundRuleNew,0);
			if (Common.isNotNull(errorMessage)){
				return R.failed(errorMessage.getMessage());
			}
			// 根据ID查询原有的公积金规则信息
			autoFundRuleOld = autoFundRuleInfoMapper.selectOne(Wrappers.<TAutoFundRuleInfo>query().lambda()
					.eq(TAutoFundRuleInfo::getMainId,autoMainRel.getId()).last(CommonConstants.LAST_ONE_SQL));
		}
		
		//公积金规则明细是否更新标识  false 未更新  true 更新
		boolean fundFlag = false;
		List<TAutoFundRuleRel> fundRuleRelsOld = null;
		//校验公积金规则明细
		List<TAutoFundRuleRel>  fundRuleRels = entity.getFundRuleRels();
		PARAM_IS_NOT_ERROR = checkFundRuleRels(fundRuleRels);
		if (PARAM_IS_NOT_ERROR != null){
			return PARAM_IS_NOT_ERROR;
		}
		
		//保存商险规则
		if (Common.isNotNull(autoInsurRuleNew)){
			if (Common.isNotNull(autoInsurRuleNew.getId())){
				autoInsurRuleInfoMapper.updateById(autoInsurRuleNew);
			}else {
				autoInsurRuleNew.setDeptNo(autoMainRel.getDeptNo());
				autoInsurRuleNew.setDeptId(autoMainRel.getDeptId());
				autoInsurRuleNew.setMainId(autoMainRel.getId());
				autoInsurRuleInfoMapper.insert(autoInsurRuleNew);
			}

			//获取旧的购买标准
			insurStandardsOld = autoInsurStandardMapper.selectList(Wrappers
					.<TAutoInsurStandard>query().lambda().eq(TAutoInsurStandard::getMainId,autoInsurRuleNew.getId()));
			//先删除后面再批增
			autoInsurStandardMapper.delete(Wrappers.<TAutoInsurStandard>query().lambda().eq(TAutoInsurStandard::getMainId,autoInsurRuleNew.getId()));
			//保存商险购买标准
			if (Common.isNotNull(insurStandards)){
				for (TAutoInsurStandard standard:insurStandards){
					if (!Common.isNotNull(standard.getId())){
						flag =true;
					}
					standard.setMainId(autoInsurRuleNew.getId());
					autoInsurStandardMapper.insert(standard);
					saveStandard(standard);
				}
			}
			//判断对象 insurStandardsOld 所有对象是否都在对象 insurStandards 里面，判断字段id
			// 在  insurStandards 中是否存在，如果不存在返回flag =true 否则返回flag =false
			flag = checkInsurStandardsForNotIn(insurStandardsOld,insurStandards);

		}
		//保存员工合同签订规则配置及方案
		if (Common.isNotNull(autoContractRuleNew)){
			if (Common.isNotNull(autoContractRuleNew.getId())){
				autoContractRuleInfoMapper.updateById(autoContractRuleNew);
			}else {
				autoContractRuleNew.setDeptNo(autoMainRel.getDeptNo());
				autoContractRuleNew.setDeptId(autoMainRel.getDeptId());
				autoContractRuleNew.setMainId(autoMainRel.getId());
				autoContractRuleInfoMapper.insert(autoContractRuleNew);
			}

			//获取旧的购买标准
			schemesOld = contractSchemeMapper.selectList(Wrappers
					.<TAutoContractScheme>query().lambda().eq(TAutoContractScheme::getMainId,autoContractRuleNew.getId()));
			//先删除后面再批增
			contractSchemeMapper.delete(Wrappers.<TAutoContractScheme>query().lambda().eq(TAutoContractScheme::getMainId,autoContractRuleNew.getId()));
			//保存员工合同标准
			TAutoContractScheme schemeTemp = null;
			if (Common.isNotNull(schemes)){
				for (TAutoContractScheme scheme:schemes){
					if (!Common.isNotNull(scheme.getId())){
						schemeFlag =true;
					}
					scheme.setDeptNo(autoMainRel.getDeptNo());
					scheme.setDeptId(autoMainRel.getDeptId());
					scheme.setMainId(autoContractRuleNew.getId());
					if (Common.isNotNull(scheme.getId())){
						schemeTemp =  contractSchemeMapper.selectOne(Wrappers.<TAutoContractScheme>query().lambda()
								.eq(TAutoContractScheme::getId,scheme.getId()).last(CommonConstants.LAST_ONE_SQL));
						if (null != schemeTemp){
							scheme.setUpdateBy(user.getId());
							scheme.setUpdateTime(LocalDateTime.now());
							contractSchemeMapper.updateById(scheme);
						}else {
							contractSchemeMapper.insert(scheme);
						}

					}else {
						contractSchemeMapper.insert(scheme);
					}
				}
			}
			// 判断数据对象是否都在页面传的对象里，有不在的数据，则返回true 目的是判断是否更新了
			schemeFlag = checkContractSchemeForNotIn(schemesOld,schemes);

		}
		//保存社保规则配置
		if (Common.isNotNull(autoSocialRuleNew)){
			if (Common.isNotNull(autoSocialRuleNew.getId())){
				autoSocialRuleNew.setUpdateBy(user.getId());
				autoSocialRuleNew.setUpdateTime(LocalDateTime.now());
				autoContractRuleNew.setMainId(autoMainRel.getId());
				autoSocialRuleInfoMapper.updateById(autoSocialRuleNew);
			}else {
				autoSocialRuleNew.setDeptNo(autoMainRel.getDeptNo());
				autoSocialRuleNew.setDeptId(autoMainRel.getDeptId());
				autoSocialRuleNew.setMainId(autoMainRel.getId());
				autoSocialRuleNew.setCreateBy(user.getId());
				autoSocialRuleNew.setCreateTime(LocalDateTime.now());
				autoSocialRuleNew.setCreateName(user.getNickname());
				autoSocialRuleInfoMapper.insert(autoSocialRuleNew);
			}
			//获取旧的社保规则明细
			if (Common.isNotNull(autoSocialRuleNew.getId())){
				//获取旧的社保规则明细
				socialRuleRelsOld = autoSocialRuleRelMapper.selectList(Wrappers
						.<TAutoSocialRuleRel>query().lambda().eq(TAutoSocialRuleRel::getMainId,autoSocialRuleNew.getId()));
				//先删除后面再批增
				autoSocialRuleRelMapper.delete(Wrappers.<TAutoSocialRuleRel>query().lambda().eq(TAutoSocialRuleRel::getMainId,autoSocialRuleNew.getId()));
			}

			//保存社保规则明细
			if (Common.isNotNull(socialRuleRels)){
				TAutoSocialRuleRel temp = null;
				for (TAutoSocialRuleRel rel:socialRuleRels){
					//存在新增的直接socialFlag =true  后面不在判断此种场景
					if (!Common.isNotNull(rel.getId())){
						socialFlag =true;
					}
					rel.setMainId(autoSocialRuleNew.getId());
					rel.setDeptNo(autoMainRel.getDeptNo());
					rel.setDeptId(autoMainRel.getDeptId());
					rel.setCreateBy(user.getId());
					rel.setCreateTime(LocalDateTime.now());
					rel.setCreateName(user.getNickname());
					if (Common.isNotNull(rel.getId())){
						temp = autoSocialRuleRelMapper.selectById(rel.getId());
						if (null != temp){
							autoSocialRuleRelMapper.updateById(rel);
						}else {
							autoSocialRuleRelMapper.insert(rel);
						}

					}else {
						autoSocialRuleRelMapper.insert(rel);
					}

				}
			}
			// 判断数据对象是否都在页面传的对象里，有不在的数据，则返回true 目的是判断是否更新了
			if (!socialFlag){
				socialFlag = checkSocialRuleRelForNotIn(socialRuleRelsOld,socialRuleRels);
			}

		}
		
		//保存公积金规则配置
		if (Common.isNotNull(autoFundRuleNew)){
			if (Common.isNotNull(autoFundRuleNew.getId())){
				autoFundRuleNew.setUpdateBy(user.getId());
				autoFundRuleNew.setUpdateTime(LocalDateTime.now());
				autoContractRuleNew.setMainId(autoMainRel.getId());
				autoFundRuleInfoMapper.updateById(autoFundRuleNew);
			}else {
				autoFundRuleNew.setDeptNo(autoMainRel.getDeptNo());
				autoFundRuleNew.setDeptId(autoMainRel.getDeptId());
				autoFundRuleNew.setMainId(autoMainRel.getId());
				autoFundRuleNew.setCreateBy(user.getId());
				autoFundRuleNew.setCreateTime(LocalDateTime.now());
				autoFundRuleNew.setCreateName(user.getNickname());
				autoFundRuleInfoMapper.insert(autoFundRuleNew);
			}
			//获取旧的公积金规则明细
			if (Common.isNotNull(autoFundRuleNew.getId())){
				//获取旧的公积金规则明细
				fundRuleRelsOld = autoFundRuleRelMapper.selectList(Wrappers
						.<TAutoFundRuleRel>query().lambda().eq(TAutoFundRuleRel::getMainId,autoFundRuleNew.getId()));
				//先删除后面再批增
				autoFundRuleRelMapper.delete(Wrappers.<TAutoFundRuleRel>query().lambda().eq(TAutoFundRuleRel::getMainId,autoFundRuleNew.getId()));
			}

			//保存公积金规则明细
			if (Common.isNotNull(fundRuleRels)){
				TAutoFundRuleRel temp = null;
				for (TAutoFundRuleRel rel:fundRuleRels){
					//存在新增的直接fundFlag =true  后面不在判断此种场景
					if (!Common.isNotNull(rel.getId())){
						fundFlag =true;
					}
					rel.setMainId(autoFundRuleNew.getId());
					rel.setDeptNo(autoMainRel.getDeptNo());
					rel.setDeptId(autoMainRel.getDeptId());
					rel.setCreateBy(user.getId());
					rel.setCreateTime(LocalDateTime.now());
					rel.setCreateName(user.getNickname());
					if (Common.isNotNull(rel.getId())){
						temp = autoFundRuleRelMapper.selectById(rel.getId());
						if (null != temp){
							autoFundRuleRelMapper.updateById(rel);
						}else {
							autoFundRuleRelMapper.insert(rel);
						}

					}else {
						autoFundRuleRelMapper.insert(rel);
					}

				}
			}
			// 判断数据对象是否都在页面传的对象里，有不在的数据，则返回true 目的是判断是否更新了
			if (!fundFlag){
				fundFlag = checkFundRuleRelForNotIn(fundRuleRelsOld,fundRuleRels);
			}

		}
		// 更新主表
	    autoMainRel.setRuleUpdatePerson(user.getNickname());
	    autoMainRel.setRuleUpdateTime(DateUtil.getCurrentDateTime());
	    baseMapper.updateById(autoMainRel);
	    // 初始化差异键值对映射
	    Map<String,String> diffKeyMap = new HashMap<>();
	    // 初始化旧数据和新数据映射
	    Map<String,Object> oldMap = new HashMap<>();
	    Map<String,Object> newMap = new HashMap<>();
	    // 比较并记录关联信息的变化
	    if (!autoMainRel.getPostFlag().equals(autoMainRelOld.getPostFlag())){
	        oldMap.put("oldRuleRel",autoMainRelOld);
	        newMap.put("newRuleRel",autoMainRel);
	        diffKeyMap.put("ruleRel","postFlag");
	    }

	    // 处理岗位字典数据
	    dictItemHandle(user, autoMainRel, autoDict, diffKeyMap, autoDictItems,oldAutoDictItems);
	    oldMap.put("oldItems",oldAutoDictItems);
	    newMap.put("newItems",autoDictItems);
		List<String> ignoreFields = new ArrayList<>();
		ignoreFields.add("mainId");
		ignoreFields.add("createBy");
		ignoreFields.add("createName");
		ignoreFields.add("createTime");
		ignoreFields.add("deptId");
		ignoreFields.add("deptNo");
		ignoreFields.add("standardInfos");
		ignoreFields.add("upperLimit");
		ignoreFields.add("lowerLimit");

		ignoreFields.add("upPersion");
		ignoreFields.add("upMedical");
		ignoreFields.add("upUnemployment");
		ignoreFields.add("upInjury");
		ignoreFields.add("upBirth");
		ignoreFields.add("upBig");
		ignoreFields.add("lowerPersion");
		ignoreFields.add("lowerMedical");
		ignoreFields.add("lowerUnemployment");
		ignoreFields.add("lowerInjury");
		ignoreFields.add("lowerBirth");
		ignoreFields.add("lowerBig");

		// 更新档案管理规则
		if (Common.isNotNull(autoEmpRuleNew)){
	        String differenceKey = HrEquator.comparisonValueIgnoreField(autoEmpRuleOld, autoEmpRuleNew,ignoreFields);
	        if (!Common.isEmpty(differenceKey)){
	            diffKeyMap.put("empRule",differenceKey);
				oldMap.put("oldEmpRule",autoEmpRuleOld);
				newMap.put("newEmpRule",autoEmpRuleNew);
	        }
	        autoEmpRuleNew.setDeptNo(autoMainRel.getDeptNo());
	        autoEmpRuleNew.setDeptId(autoMainRel.getDeptId());
	        autoEmpRuleNew.setMainId(autoMainRel.getId());
	        autoEmpRuleInfoMapper.updateById(autoEmpRuleNew);
	    }
		StringBuilder diffKeys = new StringBuilder();
		String differenceKey;
		//处理商险规则日志 -- 如果是初次创建的，则不记录日志
		if (Common.isNotNull(autoInsurRuleNew) && !Common.isEmpty(autoInsurRuleOld)){
			differenceKey = HrEquator.comparisonValueIgnoreField(autoInsurRuleOld, autoInsurRuleNew,ignoreFields);
			if (!Common.isEmpty(differenceKey)){
				diffKeyMap.put("insurRule",differenceKey);
				oldMap.put("oldInsurRule",autoInsurRuleOld);
				newMap.put("newInsurRule",autoInsurRuleNew);
			}
			//处理商险购买标准日志
			if (Common.isNotNull(insurStandards)){
				Map<String,TAutoInsurStandard> map;
				// 不为空且无新增数据，为空前面校验过了，这里不处理
				if (Common.isNotNull(insurStandards) && !flag){
					map = insurStandards.stream().collect(Collectors.toMap(TAutoInsurStandard::getId, v->v));
					if (Common.isNotNull(insurStandardsOld)){
						TAutoInsurStandard newTemp;
						for (TAutoInsurStandard old:insurStandardsOld){
							// 如果存在，则比较，不存在则标记为更新
							newTemp = map.get(old.getId());
							if (Common.isEmpty(newTemp)){
								flag = true;
								newTemp = new TAutoInsurStandard();
							}
							differenceKey = HrEquator.comparisonValueIgnoreField(old, newTemp,ignoreFields);
							if (!Common.isEmpty(differenceKey)){
								diffKeys.append(differenceKey);
								flag = true;
							}
						}
					}
				}
			}
			if (flag){
				diffKeyMap.put("insurStandardRule","standardInfos");
				oldMap.put("oldInsurStandards",insurStandardsOld);
				newMap.put("newInsurStandards",insurStandards);
			}
		}
		//处理员工合同签订规则日志
		if (Common.isNotNull(autoContractRuleNew) && !Common.isEmpty(autoContractRuleOld)){
			differenceKey = HrEquator.comparisonValueIgnoreField(autoContractRuleOld, autoContractRuleNew,ignoreFields);
			if (!Common.isEmpty(differenceKey)){
				diffKeyMap.put("contractRule",differenceKey);
				oldMap.put("oldcontractRule",autoContractRuleOld);
				newMap.put("newcontractRule",autoContractRuleNew);
			}
			//处理员工合同签订规则方案配置日志
			diffKeys = new StringBuilder();
			if (Common.isNotNull(schemes)){
				Map<String,TAutoContractScheme> map;
				// 不为空且无新增数据，为空前面校验过了，这里不处理
				if (Common.isNotNull(schemes) && !schemeFlag){
					map = schemes.stream().collect(Collectors.toMap(TAutoContractScheme::getId, v->v));
					if (Common.isNotNull(autoContractRuleOld)){
						TAutoContractScheme newTemp;
						for (TAutoContractScheme old:schemesOld){
							// 如果存在，则比较，不存在则标记为更新
							newTemp = map.get(old.getId());
							if (Common.isEmpty(newTemp)){
								schemeFlag = true;
								newTemp = new TAutoContractScheme();
							}
							differenceKey = HrEquator.comparisonValueIgnoreField(old, newTemp,ignoreFields);
							if (!Common.isEmpty(differenceKey)){
								diffKeys.append(differenceKey);
								schemeFlag = true;
							}
						}
					}
				}
			}
			if (schemeFlag){
				diffKeyMap.put("schemeRule","schemes");
				oldMap.put("oldSchemes",schemesOld);
				newMap.put("newSchemes",schemes);
			}
		}
		//处理社保规则日志 （更新时不存在规则删除的场景）
		if (Common.isNotNull(autoSocialRuleNew) && Common.isNotNull(autoSocialRuleOld)){
			differenceKey = HrEquator.comparisonValueIgnoreField(autoSocialRuleOld, autoSocialRuleNew,ignoreFields);
			if (!Common.isEmpty(differenceKey)){
				diffKeyMap.put("socialRule",differenceKey);
				oldMap.put("oldSocialRule",autoSocialRuleOld);
				newMap.put("newSocialRule",autoSocialRuleNew);
			}
			//处理社保规则明细日志
			diffKeys = new StringBuilder();
			if (Common.isNotNull(socialRuleRels)){
				Map<String,TAutoSocialRuleRel> map;
				// 不为空且无新增数据，为空前面校验过了，这里不处理
				if (Common.isNotNull(socialRuleRels) && !socialFlag){
					map = socialRuleRels.stream().collect(Collectors.toMap(TAutoSocialRuleRel::getId, v->v));
					if (Common.isNotNull(autoSocialRuleOld)){
						TAutoSocialRuleRel newTemp;
						for (TAutoSocialRuleRel old:socialRuleRelsOld){
							// 如果存在，则比较，不存在则标记为更新
							newTemp = map.get(old.getId());
							if (Common.isEmpty(newTemp)){
								socialFlag = true;
								newTemp = new TAutoSocialRuleRel();
							}
							differenceKey = HrEquator.comparisonValueIgnoreField(old, newTemp,ignoreFields);
							if (!Common.isEmpty(differenceKey)){
								diffKeys.append(differenceKey);
								socialFlag = true;
							}
						}
					}
				}
			}
			if (socialFlag){
				diffKeyMap.put("socialRuleRel","socialRuleRels");
				oldMap.put("oldSocialRuleRels",socialRuleRelsOld);
				newMap.put("newSocialRuleRels",socialRuleRels);
			}
		}
		
		//处理公积金规则日志 （更新时不存在规则删除的场景）
		if (Common.isNotNull(autoFundRuleNew) && Common.isNotNull(autoFundRuleOld)){
			differenceKey = HrEquator.comparisonValueIgnoreField(autoFundRuleOld, autoFundRuleNew,ignoreFields);
			if (!Common.isEmpty(differenceKey)){
				diffKeyMap.put("fundRule",differenceKey);
				oldMap.put("oldFundRule",autoFundRuleOld);
				newMap.put("newFundRule",autoFundRuleNew);
			}
			//处理公积金规则明细日志
			diffKeys = new StringBuilder();
			if (Common.isNotNull(fundRuleRels)){
				Map<String,TAutoFundRuleRel> map;
				// 不为空且无新增数据，为空前面校验过了，这里不处理
				if (Common.isNotNull(fundRuleRels) && !fundFlag){
					map = fundRuleRels.stream().collect(Collectors.toMap(TAutoFundRuleRel::getId, v->v));
					if (Common.isNotNull(autoFundRuleOld)){
						TAutoFundRuleRel newTemp;
						for (TAutoFundRuleRel old:fundRuleRelsOld){
							// 如果存在，则比较，不存在则标记为更新
							newTemp = map.get(old.getId());
							if (Common.isEmpty(newTemp)){
								fundFlag = true;
								newTemp = new TAutoFundRuleRel();
							}
							differenceKey = HrEquator.comparisonValueIgnoreField(old, newTemp,ignoreFields);
							if (!Common.isEmpty(differenceKey)){
								diffKeys.append(differenceKey);
								fundFlag = true;
							}
						}
					}
				}
			}
			if (fundFlag){
				diffKeyMap.put("fundRuleRel","fundRuleRels");
				oldMap.put("oldFundRuleRels",fundRuleRelsOld);
				newMap.put("newFundRuleRels",fundRuleRels);
			}
		}
		// 插入变更日志
	    insertLog(autoMainRel, diffKeyMap, oldMap, newMap);
	    // 返回更新成功的响应
	    return R.ok(true,CommonConstants.UPDATE_SUCCESS);
	}

	private boolean checkContractSchemeForNotIn(List<TAutoContractScheme> schemes, List<TAutoContractScheme> schemesOld) {
		if (Common.isEmpty(schemes) && !Common.isEmpty(schemesOld)) {
			return true; // 数据库数据无 新增有 返回true
		}
		if (!Common.isEmpty(schemes) && Common.isEmpty(schemesOld)) {
			return true; // 数据库有 新增无返回 true
		}
		// 不为空判断
		if (!Common.isEmpty(schemes) && !Common.isEmpty(schemesOld)) {
			Set<String> existingKeys = schemes.stream()
					.map(scheme -> Optional.ofNullable(scheme.getId()).orElse(""))
					.collect(Collectors.toSet());
			for (TAutoContractScheme scheme : schemesOld) {
				if (!existingKeys.contains(scheme.getId())) {
					return true; // 存在不在现有集合中的数据，表示需要处理
				}
			}
		}
		return false; // 所有数据都在现有集合中，无需额外处理
	}

	/**
	 * @Author fxj
	 * @Description 校验商险标准是否不在已存在的集合中
	 * @Date 10:24 2025/6/11
	 **/
	private boolean checkInsurStandardsForNotIn(List<TAutoInsurStandard> insurStandards, List<TAutoInsurStandard> existingStandards) {
		if (Common.isEmpty(insurStandards) && !Common.isEmpty(existingStandards)) {
			return true; // 数据库数据无 新增有 返回true
		}
		if (!Common.isEmpty(insurStandards) && Common.isEmpty(existingStandards)) {
			return true; // 数据库有 新增无返回 true
		}
		// 不为空判断
		if (!Common.isEmpty(insurStandards) && !Common.isEmpty(existingStandards)) {
			Set<String> existingKeys = existingStandards.stream()
					.map(standard -> Optional.ofNullable(standard.getId()).orElse(""))
					.collect(Collectors.toSet());
			for (TAutoInsurStandard standard : insurStandards) {
				if (!existingKeys.contains(standard.getId())) {
					return true; // 存在不在现有集合中的数据，表示需要处理
				}
			}
		}
		return false; // 所有数据都在现有集合中，无需额外处理
	}

	private void saveStandard(TAutoInsurStandard standard) {
		if (Common.isNotNull(standard.getStandardInfos())){
			autoStandardInfoMapper.delete(Wrappers.<TAutoStandardInfo>query().lambda()
					.eq(TAutoStandardInfo::getMainId,standard.getId()));
			for (TAutoStandardInfo standardInfo: standard.getStandardInfos()){
				standardInfo.setMainId(standard.getId());
				autoStandardInfoMapper.insert(standardInfo);
			}
		}
	}

	private Map<String, SysAutoDictItem> getStringSysAutoDictItemMap(List<SysAutoDictItem> autoDictItems, Map<String, SysAutoDictItem> repeatItems, List<SysAutoDictItem> oldAutoDictItems) {
		if (Common.isNotNull(oldAutoDictItems)){
			repeatItems = oldAutoDictItems.stream().collect(Collectors.toMap(SysAutoDictItem::getLabel, v->v,(k1, k2)->k1));
			//数据库中查询的字典 页面已经改了 不在作为重复结果集
			for (SysAutoDictItem item: oldAutoDictItems){
				for (SysAutoDictItem item1: autoDictItems){
					if (Common.isNotNull(item1.getId()) && CommonConstants.ONE_STRING.equals(item1.getDisable())){
						repeatItems.remove(item1.getLabel());
					}
					if (Common.isNotNull(item1.getId())
							&& item.getId().equals(item1.getId())
							&& !item1.getLabel().equals(item.getLabel())){
						repeatItems.remove(item.getLabel());
					}
				}
			}

		}
		return repeatItems;
	}

	/**
 * 检查字典项列表中是否存在重复的标签
 * 此方法用于确保在同一字典下不存在重复的字典项标签
 * 它通过比较给定的字典项列表与一个用于跟踪重复项的映射来实现这一点
 *
 * @param autoDictItems 字典项列表，用于检查重复的标签
 * @param repeatItems 一个映射，用于跟踪已经遇到的字典项，键为字典项标签
 * @return 如果存在重复且未被禁用的字典项，则返回一个表示失败的结果对象；
 *         否则，返回 null 表示检查通过或输入参数为空
 */
private R<Boolean> checkItemRepeat(List<SysAutoDictItem> autoDictItems, Map<String, SysAutoDictItem> repeatItems) {
    // 校验输入参数是否为 null
    if (Common.isEmpty(autoDictItems)) {
        return null; // 根据业务需求决定返回值
    }
	Map<String,String> labelRepeat = new HashMap<>();
    for (SysAutoDictItem item : autoDictItems) {
		//自循环查询是否重复
		if (CommonConstants.ZERO_STRING.equals(item.getDisable()) && labelRepeat.put(item.getLabel(),"") != null){
			return R.failed(itemsLabelRepeat);
		}
        if (Common.isEmpty(item)
				|| Common.isEmpty(item.getLabel())
				|| CommonConstants.ONE_STRING.equals(item.getDisable())) {
            continue; // 跳过无效的 item
        }
		//和已有岗位是否重复
        SysAutoDictItem checkItem = null == repeatItems?null:repeatItems.get(item.getLabel());
        if (checkItem != null) {
            // 检查是否存在重复项
            if (CommonConstants.ZERO_STRING.equals(checkItem.getDisable())
                    && (Common.isEmpty(checkItem.getId()) || !checkItem.getId().equals(item.getId()))) {
                return R.failed(itemsLabelRepeat);
            }
        }

        // 将当前 item 放入 repeatItems 中
        try {
            repeatItems.put(item.getLabel(), item);
        } catch (Exception e) {
            // 捕获异常并记录日志（根据实际需求决定是否抛出）
            log.error("校验字典重复时异常: " + e.getMessage());
            return R.failed("Internal error occurred");
        }
    }

    return null;
}


	/**
	 * @Author fxj
	 * @Description 功能概述：dictItemHandle 方法用于处理字典项的更新或新增操作，同时记录差异字段。
	 * @Date 17:09 2025/3/20
	**/
	private void dictItemHandle(YifuUser user,
								TAutoMainRel autoMainRel,
								SysAutoDict autoDict,
								Map<String, String> diffKeyMap,
								List<SysAutoDictItem> autoDictItems,
								List<SysAutoDictItem> oldAutoDictItems) {

		if (Common.isNotNull(autoDictItems)){
			// 初始化旧字典项映射
			Map<Long, SysAutoDictItem> oldItemMap = null;
			if (Common.isNotNull(oldAutoDictItems)){
				oldItemMap = oldAutoDictItems.stream().collect(Collectors.toMap(SysAutoDictItem::getId, v->v));
			}
			SysAutoDictItem oldItem;
			String diffKey;
			// 初始化差异字段存储
			Set<String> diffKeysSet = new HashSet<>();
			List<String> ignoreFields = Arrays.asList("value", "sortOrder");
			for(SysAutoDictItem sysAutoDictItem : autoDictItems){
				initDictItem(sysAutoDictItem, user, autoDict, autoMainRel);
				if (Common.isNotNull(sysAutoDictItem.getId())){
					oldItem = null==oldItemMap?null:oldItemMap.get(sysAutoDictItem.getId());
					if (Common.isNotNull(oldItem)) {
						diffKey = HrEquator.comparisonValueIgnoreField(oldItem, sysAutoDictItem, ignoreFields);
						if (Common.isNotNull(diffKey)) {
							diffKeysSet.add(diffKey);
						}
					}
					try {
						autoDictItemMapper.updateById(sysAutoDictItem);
					} catch (Exception e) {
						// 记录异常日志并继续处理其他项
						log.error("Failed to update dictionary item with ID: {}", sysAutoDictItem.getId(), e);
					}
				}else {
					diffKeysSet.add(itemsLabel);
					sysAutoDictItem.setCreateTime(LocalDateTime.now());
					sysAutoDictItem.setCreateBy(user.getId());
					sysAutoDictItem.setCreateName(user.getNickname());
					try {
						autoDictItemMapper.insert(sysAutoDictItem);
					} catch (Exception e) {
						// 记录异常日志并继续处理其他项
						log.error("Failed to insert dictionary item: {}", sysAutoDictItem, e);
					}
				}
			}
			// 将差异字段集合转换为字符串并存入 diffKeyMap
			if (!diffKeysSet.isEmpty()) {
				String keysStr = String.join(CommonConstants.COMMA_STRING, diffKeysSet);
				diffKeyMap.put("postType", keysStr);
			}
		}
	}

	/**
	 * @Author fxj
	 * @Description 插入变更日志
	 * @Date 15:43 2025/3/14
	**/
	private void insertLog(TAutoMainRel autoMainRel, Map<String, String> diffKeyMap, Map<String, Object> oldMap, Map<String, Object> newMap) {
		try{
			//比较记录不影响业务逻辑，用try套住
			//如果有差异保存差异
			if(!Common.isEmpty(diffKeyMap)){
				TAutoRuleLog log = new TAutoRuleLog();
				log.setType(0);
				log.setMainId(autoMainRel.getId());
				log.setCreateTime(LocalDateTime.now());
				log.setOldInfo(JSON.toJSONString(oldMap,features));
				log.setNewInfo(JSON.toJSONString(newMap,features));
				log.setDifferenceInfo(JSON.toJSONString(diffKeyMap,features));
				autoRuleLogMapper.insert(log);
			}
		}catch (Exception e){
			log.error(JSON.toJSON(oldMap)+"插入修改记录报错>>>",e);
		}
	}
	/**
	 * @Author fxj
	 * @Description 初始化字典项信息公共方法
	 * @Date 15:43 2025/3/14
	**/
	private void initDictItem(SysAutoDictItem sysAutoDictItem, YifuUser user, SysAutoDict autoDict, TAutoMainRel autoMainRel) {
		sysAutoDictItem.setUpdateTime(LocalDateTime.now());
		sysAutoDictItem.setUpdateBy(user.getId());
		sysAutoDictItem.setDelFlag(CommonConstants.ZERO_STRING);
		sysAutoDictItem.setClientId(ServiceNameConstants.SERVICE_CLIENT_ID_MVP);
		sysAutoDictItem.setDictId(autoDict.getId());
		sysAutoDictItem.setType(CommonConstants.POST_TYPE);
		if (Common.isEmpty(sysAutoDictItem.getDisable())){
			sysAutoDictItem.setDisable(CommonConstants.ZERO_STRING);
		}
		sysAutoDictItem.setDeptNo(autoMainRel.getDeptNo());
	}

	private SerializerFeature[] features = new SerializerFeature[] {
			WriteMapNullValue, WriteNullNumberAsZero, WriteNullListAsEmpty,
			WriteNullStringAsEmpty,WriteDateUseDateFormat
	};


	@Override
	public R<TAutoMainRelDetailVo> getProjectRule(String deptId, String deptNo) {
		if (Common.isEmpty(deptId) && Common.isEmpty(deptNo)){
			return R.failed(CommonConstants.PARAM_IS_NOT_ERROR);
		}
		LambdaQueryWrapper<TAutoMainRel> wrapper = buildQueryWrapper(deptId,deptNo);
		TAutoMainRel rel = baseMapper.selectOne(wrapper);
		if (Common.isNotNull(rel) && Common.isNotNull(rel.getId())){
			return this.getByIdAsso(rel.getId());
		}
		return R.ok();
	}

	/**
	 * @Author fxj
	 * @Description 员工合同签订规则-方案分页查询
	 * @Date 14:33 2025/6/13
	**/
	@Override
	public IPage<TAutoContractScheme> getContractSchemePage(Page<TAutoContractScheme> page, TAutoContractScheme search) {
		return contractSchemeMapper.getTAutoContractSchemePage(page,search);
	}

	private LambdaQueryWrapper buildQueryWrapper(String deptId, String deptNo){
		LambdaQueryWrapper<TAutoMainRel> wrapper = Wrappers.lambdaQuery();
		if (ArrayUtil.isNotEmpty(deptId)) {
			wrapper.ge(TAutoMainRel::getDeptId, deptId);
		}
		if (Common.isNotNull(deptNo)){
			wrapper.eq(TAutoMainRel::getDeptNo,deptNo);
		}
		return wrapper;
	}
	/**
	 * @Author fxj
	 * @Description 远程接口获取项目对应商险的自动化配置信息，有商险自动化且配置'是否仅使用自动化入口'  为是的需要强制限制
	 * @Date 11:26 2025/9/17
	 **/
	@Override
	public Map<String, String> getProjectAutoSetMap(List<String> departNos) {
		Map<String,String> map = new HashMap<>();
		//如果配置了'是否仅使用自动化入口' 为是的需要强制限制
		List<TAutoMainRel> list = baseMapper.selectList(Wrappers.<TAutoMainRel>query().lambda());
		if(Common.isNotNull(list)){
			for(TAutoMainRel vo :list){
				if(CommonConstants.ZERO_STRING.equals(vo.getAutoFlag())){
					map.put(vo.getDeptNo(),vo.getDeptNo());
				}
			}
		}
		return map;
	}

	/**
	 * @Description: 获取全量自动化项目，value里是续保周期
	 * @Author: hgw
	 * @Date: 2025/11/12 18:15
	 * @return: com.yifu.cloud.plus.v1.yifu.insurances.vo.AutoDeptVO
	 **/
	@Override
	public AutoDeptVO getAutoDeptMap() {
		Map<String, AutoDeptDetailVO> returnMap = new HashMap<>();
		List<TAutoMainRel> list = baseMapper.getAutoDeptMap();
		if(Common.isNotNull(list)) {
			AutoDeptDetailVO detailVO;
			Integer month;
			for(TAutoMainRel vo :list) {
				detailVO = new AutoDeptDetailVO();
				try {
					month = Integer.parseInt(vo.getId());
				} catch (Exception e) {
					month = CommonConstants.ONE_INT;
					log.info("转化周期失败，默认1月: {}", e);
				}
				detailVO.setNum( month);
				detailVO.setCustomerUsername(vo.getCsUserName());
				detailVO.setCustomerUserLoginame(vo.getCsLoginName());
				returnMap.put(vo.getDeptNo(), detailVO);
			}
		}
		AutoDeptVO returnVo = new AutoDeptVO();
		returnVo.setDeptMap(returnMap);
		return returnVo;
	}

	/**
	 * @Author fxj
	 * @Description 校验社保规则
	 * @Date 10:24 2025/6/11
	 **/
	private R<Boolean> checkSocialRuleRels(List<TAutoSocialRuleRel> socialRuleRels) {
		if (Common.isNotNull(socialRuleRels)){
			ExcelUtil<TAutoSocialRuleRel> excelUtil = new ExcelUtil<>(TAutoSocialRuleRel.class);
			ErrorMessage errorMessage;
			for (TAutoSocialRuleRel rel: socialRuleRels){
				errorMessage =  excelUtil.checkEntity(rel,0);
				if (Common.isNotNull(errorMessage)){
					return R.failed(errorMessage.getMessage());
				}
				//针对"备案基数类型"为"固定值"时,"备案基数"必填,"缴纳类型"为"最高或最低"
				//时，配置提交时，会将"备案基数"同该社保户对应的最高或最低的基数进行对比，"备案基
				//数"等于社保户的最高或最低基数
				if (CommonConstants.ZERO_STRING.equals(rel.getRecordBaseType())){
					if (!Common.isNotNull(rel.getRecordBase())){
						return R.failed("备案基数不可空");
					}
					if ((CommonConstants.ZERO_STRING.equals(rel.getPaymentType())
							|| CommonConstants.TWO_STRING.equals(rel.getPaymentType()))){
						R<SysBaseSetInfoVo> resR = socialDaprUtils.getSocialHouseBaseSet(rel.getConfigHouseId());
						if (Common.isNotNull(resR) && resR.getData() != null) {
							SysBaseSetInfoVo setInfo = resR.getData();
							if (Common.isNotNull(setInfo)) {
								try {
									// 添加了异常处理，避免 recordBase 不是合法数字格式时程序崩溃
									if (CommonConstants.ZERO_STRING.equals(rel.getPaymentType())){
										BigDecimal recordBaseDecimal = new BigDecimal(rel.getRecordBase());
										if (CommonConstants.ZERO_STRING.equals(setInfo.getIsSameBase())){
											if (recordBaseDecimal.compareTo(setInfo.getLowerLimit()) > 0) {
												return R.failed("备案基数不大于配置名称("+rel.getConfigName()+")最低基数:"+setInfo.getLowerLimit());
											}
										}else {
											if (recordBaseDecimal.compareTo(setInfo.getLowerPersion()) > 0) {
												return R.failed("备案基数不大于配置名称("+rel.getConfigName()+")最低基数:"+setInfo.getLowerPersion());
											}else if (recordBaseDecimal.compareTo(setInfo.getLowerMedical()) > 0) {
												return R.failed("备案基数不大于配置名称("+rel.getConfigName()+")最低基数:"+setInfo.getLowerMedical());
											}else if (recordBaseDecimal.compareTo(setInfo.getLowerBirth()) > 0) {
												return R.failed("备案基数不大于配置名称("+rel.getConfigName()+")最低基数:"+setInfo.getLowerBirth());
											}else if (recordBaseDecimal.compareTo(setInfo.getLowerInjury()) > 0) {
												return R.failed("备案基数不大于配置名称("+rel.getConfigName()+")最低基数:"+setInfo.getLowerInjury());
											}else if (recordBaseDecimal.compareTo(setInfo.getLowerUnemployment()) > 0) {
												return R.failed("备案基数不大于配置名称("+rel.getConfigName()+")最低基数:"+setInfo.getLowerUnemployment());
											}

										}

									}
								} catch (NumberFormatException e) {
									return R.failed("备案基数格式不正确");
								}
							}
						}else {
							return R.failed("获取社保配置信息失败！");
						}
					}
				}
			}
			// 校验socialRuleRels 配置名称是否重复
			Set<String> names = socialRuleRels.stream().map(TAutoSocialRuleRel::getConfigName).collect(Collectors.toSet());
			if (names.size() != socialRuleRels.size()) {
				return R.failed(schemeNameRepeat);
			}
		}
		return null;
	}
	
	/**
	 * @Author fxj
	 * @Description 校验社保规则明细是否不在已存在的集合中
	 * @Date 10:24 2025/6/11
	 **/
	private boolean checkSocialRuleRelForNotIn(List<TAutoSocialRuleRel> socialRuleRels, List<TAutoSocialRuleRel> existingRuleRels) {
		if (Common.isEmpty(socialRuleRels) && !Common.isEmpty(existingRuleRels)) {
			return true; // 数据库数据无 新增有 返回true
		}
		if (!Common.isEmpty(socialRuleRels) && Common.isEmpty(existingRuleRels)) {
			return true; // 数据库有 新增无返回 true
		}
		// 不为空判断
		if (!Common.isEmpty(socialRuleRels) && !Common.isEmpty(existingRuleRels)) {
			Set<String> existingKeys = existingRuleRels.stream()
					.map(standard -> Optional.ofNullable(standard.getId()).orElse(""))
					.collect(Collectors.toSet());
			for (TAutoSocialRuleRel standard : socialRuleRels) {
				if (!existingKeys.contains(standard.getId())) {
					return true; // 存在不在现有集合中的数据，表示需要处理
				}
			}
		}
		return false; // 所有数据都在现有集合中，无需额外处理
	}

	/**
	 * @Author fxj
	 * @Description 校验公积金规则
	 * @Date 10:24 2025/6/11
	 **/
	private R<Boolean> checkFundRuleRels(List<TAutoFundRuleRel> fundRuleRels) {
		if (Common.isNotNull(fundRuleRels)){
			ExcelUtil<TAutoFundRuleRel> excelUtil = new ExcelUtil<>(TAutoFundRuleRel.class);
			ErrorMessage errorMessage;
			for (TAutoFundRuleRel rel: fundRuleRels){
				errorMessage =  excelUtil.checkEntity(rel,0);
				if (Common.isNotNull(errorMessage)){
					return R.failed(errorMessage.getMessage());
				}
				//初始化最高最低基数及省市县
				if (!Common.isNotNull(rel.getConfigHouseId())){
					return R.failed("公积金户不可为空");
				}
				R<SysBaseSetInfoVo> resR = socialDaprUtils.getSocialHouseBaseSet(rel.getConfigHouseId());
				if (Common.isNotNull(resR) && resR.getData() != null) {
					SysBaseSetInfoVo setInfo = resR.getData();
					rel.setLowerLimit(setInfo.getLowerLimit());
					rel.setUpperLimit(setInfo.getUpperLimit());
					rel.setProvince(setInfo.getProvince());
					rel.setCity(setInfo.getCity());
					rel.setTown(setInfo.getTown());
					if (CommonConstants.THREE_STRING.equals(rel.getPaymentType())){
						if (rel.getFundBase().compareTo(setInfo.getLowerLimit()) < 0) {
							return R.failed("公积金基数需≥当前户("+setInfo.getDepartName()+")的最低基数:"+setInfo.getLowerLimit()+"！");
						}
					}

				}else {
					return R.failed("获取公积金配置信息失败！");
				}
			}
			// 校验fundRuleRels 配置名称是否重复
			Set<String> names = fundRuleRels.stream().map(TAutoFundRuleRel::getConfigName).collect(Collectors.toSet());
			if (names.size() != fundRuleRels.size()) {
				return R.failed(schemeNameRepeat);
			}
		}
		return null;
	}
	
	/**
	 * @Author fxj
	 * @Description 校验公积金规则明细是否不在已存在的集合中
	 * @Date 10:24 2025/6/11
	 **/
	private boolean checkFundRuleRelForNotIn(List<TAutoFundRuleRel> fundRuleRels, List<TAutoFundRuleRel> existingRuleRels) {
		if (Common.isEmpty(fundRuleRels) && !Common.isEmpty(existingRuleRels)) {
			return true; // 数据库数据无 新增有 返回true
		}
		if (!Common.isEmpty(fundRuleRels) && Common.isEmpty(existingRuleRels)) {
			return true; // 数据库有 新增无返回 true
		}
		// 不为空判断
		if (!Common.isEmpty(fundRuleRels) && !Common.isEmpty(existingRuleRels)) {
			Set<String> existingKeys = existingRuleRels.stream()
					.map(standard -> Optional.ofNullable(standard.getId()).orElse(""))
					.collect(Collectors.toSet());
			for (TAutoFundRuleRel standard : fundRuleRels) {
				if (!existingKeys.contains(standard.getId())) {
					return true; // 存在不在现有集合中的数据，表示需要处理
				}
			}
		}
		return false; // 所有数据都在现有集合中，无需额外处理
	}

	@Override
	public R<Boolean> updateAutoFlagById(String id, String autoFlag) {
		if (Common.isEmpty(id)
				|| Common.isEmpty(autoFlag)
				|| (!CommonConstants.ZERO_STRING.equals(autoFlag)
				&& !CommonConstants.ONE_STRING.equals(autoFlag))){
			return R.failed(CommonConstants.PARAM_IS_NOT_ERROR);
		}
		TAutoMainRel autoMainRel = baseMapper.selectById(id);
		if (null == autoMainRel){
			return R.failed(CommonConstants.PARAM_INFO_ERROR);
		}
		TAutoMainRel autoMainRelNew = new TAutoMainRel();
		BeanUtils.copyProperties(autoMainRel,autoMainRelNew);
		autoMainRelNew.setAutoFlag(autoFlag);

		if (baseMapper.updateById(autoMainRelNew) >=0){
			if (!autoMainRelNew.getAutoFlag().equals(autoMainRel.getAutoFlag())){
				Map<String,String> diffKeyMap = new HashMap<>();
				Map<String,Object> oldMap = new HashMap<>();
				Map<String,Object> newMap = new HashMap<>();
				diffKeyMap.put("autoMailRel","autoMailRel");
				oldMap.put("oldAutoMailRel",autoMainRel);
				newMap.put("newAutoMailRel",autoMainRelNew);
				insertLog(autoMainRel, diffKeyMap, oldMap, newMap);
			}
			return R.ok();
		}
		return R.failed();
	}
}