/*
 *    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.security.util.SecurityUtils;
import lombok.extern.log4j.Log4j2;
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.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;

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

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

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

    /**
     * 项目配置表主表简单分页查询
     * @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);
		}
		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);
			}
			//新增主表
			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);
				}
			}
			return R.ok();
		}catch (Exception e){
			// 捕获异常并返回友好提示
			return R.failed("系统异常：" + e.getMessage());
		}
	}

	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;
	}

	private boolean checkInsurStandardsForDuplicates(List<TAutoInsurStandard> insurStandards) {
		if (Common.isNotNull(insurStandards)) {
			Map<String,String> map = new HashMap<>();
			for (TAutoInsurStandard standard : insurStandards) {
				if (map.put(standard.getCompany() + standard.getRiskType() + standard.getStandard(), "") != null){
					return true;
				}
				if (map.put(standard.getName() , "") != null){
					return true;
				}
			}
			map.clear();
		}
		return false;
	}

	/**
	 * 检查字典项是否有重复标签
	 */
	private boolean checkDictItemsForDuplicates(List<SysAutoDictItem> autoDictItems) {
		Set<String> repeatItems = new HashSet<>();
		for (SysAutoDictItem item : autoDictItems) {
			if (Common.isEmpty(item.getLabel())) {
				return false; // 标签为空视为无效
			}
			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 = null;
		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);
			}
			//校验商险购买标准
			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);
			}
			//获取旧的购买标准
			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);
				}
			}
		}
	    // 更新岗位字典
	    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;
	    }
	    // 更新主表
	    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");

		// 更新档案管理规则
		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);
	    }
		//处理商险规则日志
		if (Common.isNotNull(autoInsurRuleNew)){
			if (Common.isEmpty(autoInsurRuleOld)){
				autoInsurRuleOld = new TAutoInsurRuleInfo();
			}
			String differenceKey = HrEquator.comparisonValueIgnoreField(autoInsurRuleOld, autoInsurRuleNew,ignoreFields);
			if (!Common.isEmpty(differenceKey)){
				diffKeyMap.put("insurRule",differenceKey);
				oldMap.put("oldInsurRule",autoInsurRuleOld);
				newMap.put("newInsurRule",autoInsurRuleNew);
			}
		}
		//处理商险购买标准日志
		StringBuilder diffKeys = new StringBuilder();
		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)){
					String differenceKey;
					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);
			}
		}
		// 插入变更日志
	    insertLog(autoMainRel, diffKeyMap, oldMap, newMap);
	    // 返回更新成功的响应
	    return R.ok(true,CommonConstants.UPDATE_SUCCESS);
	}

	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();
	}
	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;
	}
}
