/*
 *    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.social.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.alibaba.excel.util.ListUtils;
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.admin.api.entity.SysUser;
import com.yifu.cloud.plus.v1.yifu.archives.vo.SocialAuthHandleImportVo;
import com.yifu.cloud.plus.v1.yifu.archives.vo.SocialAuthImportVo;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.Common;
import com.yifu.cloud.plus.v1.yifu.common.core.util.ErrorMessage;
import com.yifu.cloud.plus.v1.yifu.common.core.util.ExcelUtil;
import com.yifu.cloud.plus.v1.yifu.common.core.util.R;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.UpmsDaprUtils;
import com.yifu.cloud.plus.v1.yifu.social.entity.SysBaseSetInfo;
import com.yifu.cloud.plus.v1.yifu.social.entity.SysHouseHoldInfo;
import com.yifu.cloud.plus.v1.yifu.social.entity.TSocialfundHouseRes;
import com.yifu.cloud.plus.v1.yifu.social.mapper.TSocialfundHouseResMapper;
import com.yifu.cloud.plus.v1.yifu.social.service.SysBaseSetInfoService;
import com.yifu.cloud.plus.v1.yifu.social.service.TSocialfundHouseResService;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.shardingsphere.transaction.annotation.ShardingTransactionType;
import org.apache.shardingsphere.transaction.core.TransactionType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 社保公积金户权限配置表
 *
 * @author huyc
 * @date 2022-11-02 09:13:07
 */
@Log4j2
@AllArgsConstructor
@Service
public class TSocialfundHouseResServiceImpl extends ServiceImpl<TSocialfundHouseResMapper, TSocialfundHouseRes> implements TSocialfundHouseResService {
	@Autowired
	private UpmsDaprUtils upmsDaprUtils;
	private SysBaseSetInfoService baseSetInfoService;
    /**
     * 社保公积金户权限配置表简单分页查询
     * @param tSocialfundHouseRes 社保公积金户权限配置表
     * @return
     */
    @Override
    public IPage<TSocialfundHouseRes> getTSocialfundHouseResPage(Page<TSocialfundHouseRes> page, TSocialfundHouseRes tSocialfundHouseRes){
        return baseMapper.getTSocialfundHouseResPage(page,tSocialfundHouseRes);
    }
	/**
     * 社保公积金户权限配置表批量导出
     * @param searchVo 社保公积金户权限配置表
     * @return
     */
    @Override
    public List<TSocialfundHouseRes> getexportList(TSocialfundHouseRes searchVo) {
		if (!Common.isNotNull(searchVo.getHouseNameType())) {
			searchVo.setAuthType(CommonConstants.ZERO_STRING);
		} else if (CommonConstants.ZERO_STRING.equals(searchVo.getHouseNameType())){
			searchVo.setAuthType(CommonConstants.ONE_STRING);
		}
        return baseMapper.getexportList(searchVo);
    }

	@Override
	public R saveSocialAuth(TSocialfundHouseRes searchVo) {
		LambdaQueryWrapper<TSocialfundHouseRes> wrapper = new LambdaQueryWrapper<>();
		if (Common.isNotNull(searchVo.getSocialHousehold())) {
			wrapper.eq(TSocialfundHouseRes::getSocialHousehold, searchVo.getSocialHousehold());
		}
		if (Common.isNotNull(searchVo.getFundHousehold())){
			wrapper.eq(TSocialfundHouseRes::getFundHousehold,searchVo.getFundHousehold());
		}
		if (Common.isNotNull(searchVo.getUserId())){
			wrapper.eq(TSocialfundHouseRes::getUserId,searchVo.getUserId());
		}
		if (Common.isNotNull(searchVo.getAuthType())){
			wrapper.eq(TSocialfundHouseRes::getAuthType,searchVo.getAuthType());
		}
		wrapper.last(CommonConstants.LAST_ONE_SQL);
		TSocialfundHouseRes socialfundHouseRes = baseMapper.selectOne(wrapper);
		if (Common.isNotNull(socialfundHouseRes)) {
			String errorMessage;
			if (CommonConstants.ZERO_STRING.equals(searchVo.getAuthType())) {
				errorMessage = "请勿重复添加审核人员";
			} else {
				errorMessage = "请勿重复添加办理人员";
			}
			return R.failed(errorMessage);
		} else {
			baseMapper.insert(searchVo);
			return R.ok();
		}
	}

	@Override
	public void deleteAuditUser(SysHouseHoldInfo holdInfo) {
		if (Common.isNotNull(holdInfo.getType()) && Common.isNotNull(holdInfo.getName())
				&& Common.isNotNull(holdInfo.getAuditUser())) {
			// 审核权限
			TSocialfundHouseRes searchVo = new TSocialfundHouseRes();
			if (CommonConstants.ZERO_STRING.equals(holdInfo.getType())) {
				searchVo.setSocialHousehold(holdInfo.getName());
			} else {
				searchVo.setFundHousehold(holdInfo.getName());
			}
			searchVo.setUserId(holdInfo.getAuditUser());
			searchVo.setAuthType(CommonConstants.ZERO_STRING);
			baseMapper.deleteByUserIdAndHuName(searchVo);
		}
	}

	@Override
	public void deleteHandleUser(SysHouseHoldInfo holdInfo) {
		if (Common.isNotNull(holdInfo.getType()) && Common.isNotNull(holdInfo.getName())
				&& Common.isNotNull(holdInfo.getHandleUser())) {
			// 办理权限
			TSocialfundHouseRes searchVo = new TSocialfundHouseRes();
			if (CommonConstants.ZERO_STRING.equals(holdInfo.getType())) {
				searchVo.setSocialHousehold(holdInfo.getName());
			} else {
				searchVo.setFundHousehold(holdInfo.getName());
			}
			searchVo.setUserId(holdInfo.getHandleUser());
			searchVo.setAuthType(CommonConstants.ONE_STRING);
			baseMapper.deleteByUserIdAndHuName(searchVo);
		}
	}

	/**
	 * @Author fxj
	 * @Description 批量新增社保公积金审核权限
	 * @Date 16:59 2023/10/17
	 * @Param
	 * @return
	 **/
	@Transactional(rollbackFor = Exception.class)
	@ShardingTransactionType(TransactionType.BASE)
	@Override
	public R<List<ErrorMessage>> importDiy(InputStream inputStream) {
		List<ErrorMessage> errorMessageList = new ArrayList<>();
		ExcelUtil<SocialAuthImportVo> util1 = new ExcelUtil<>(SocialAuthImportVo.class);
		Map<String, SysBaseSetInfo> fundBaseSetMap = null;
		Map<String, SysBaseSetInfo> socialBaseSetMap = null;
		// 获取社保公积金配置
		List<SysBaseSetInfo>  socialSet = baseSetInfoService.list(Wrappers.<SysBaseSetInfo>query().lambda()
				.eq(SysBaseSetInfo::getBaseType,CommonConstants.ZERO_STRING)
				.eq(SysBaseSetInfo::getDeleteFlag,CommonConstants.ZERO_STRING)
				.groupBy(SysBaseSetInfo::getDepartName,SysBaseSetInfo::getProvince,SysBaseSetInfo::getCity,SysBaseSetInfo::getTown));
		if (Common.isNotNull(socialSet)){
			socialBaseSetMap = socialSet.stream().collect(Collectors.toMap(k->k.getDepartName(), k->k));
		}
		List<SysBaseSetInfo>  fundSet = baseSetInfoService.list(Wrappers.<SysBaseSetInfo>query().lambda()
				.eq(SysBaseSetInfo::getBaseType,CommonConstants.ONE_STRING)
				.eq(SysBaseSetInfo::getDeleteFlag,CommonConstants.ZERO_STRING)
				.groupBy(SysBaseSetInfo::getDepartName,SysBaseSetInfo::getProvince,SysBaseSetInfo::getCity,SysBaseSetInfo::getTown));
		if (Common.isNotNull(fundSet)){
			fundBaseSetMap = fundSet.stream().collect(Collectors.toMap(k->k.getDepartName(), k->k));
		}
		if (Common.isEmpty(socialBaseSetMap) || Common.isEmpty(fundBaseSetMap)){
			return R.failed("获取社保及公积金户配置信息失败！");
		}
		Map<String, SysUser> userMap = new HashMap<>();
		Map<String,String> existMap = new HashMap<>();
		// 写法2：
		// 匿名内部类 不用额外写一个DemoDataListener
		// 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
		try {
			Map<String, SysBaseSetInfo> finalSocialBaseSetMap = socialBaseSetMap;
			Map<String, SysBaseSetInfo> finalFundBaseSetMap = fundBaseSetMap;
			EasyExcel.read(inputStream, SocialAuthImportVo.class, new ReadListener<SocialAuthImportVo>() {
				/**
				 * 单次缓存的数据量
				 */
				public static final int BATCH_COUNT = CommonConstants.BATCH_COUNT;
				/**
				 *临时存储
				 */
				private List<SocialAuthImportVo> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

				@Override
				public void invoke(SocialAuthImportVo data, AnalysisContext context) {
					ReadRowHolder readRowHolder = context.readRowHolder();
					Integer rowIndex = readRowHolder.getRowIndex();
					data.setRowIndex(rowIndex+1);
					ErrorMessage errorMessage = util1.checkEntity(data, data.getRowIndex());
					if (Common.isNotNull(errorMessage)){
						errorMessage.setData(data);
						errorMessageList.add(errorMessage);
					}else {
						cachedDataList.add(data);
					}
					if (cachedDataList.size() >= BATCH_COUNT) {
						saveData();
						// 存储完成清理 list
						cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
					}
				}
				@Override
				public void doAfterAllAnalysed(AnalysisContext context) {
					saveData();
				}

				/**
				 * 加上存储数据库
				 */
				private void saveData() {
					log.info("{}条数据，开始存储数据库！", cachedDataList.size());
					importEntity(cachedDataList,errorMessageList, finalSocialBaseSetMap, finalFundBaseSetMap,userMap,existMap);
					log.info("存储数据库成功！");
				}
			}).sheet().doRead();
		}catch (Exception e){
			log.error(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR,e);
			return R.failed(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR);
		}finally {
			// 清理
			socialBaseSetMap.clear();
			fundBaseSetMap.clear();
		}

		return  judgeAllMessage(errorMessageList);
	}

	private void importEntity(List<SocialAuthImportVo> excelVOList,
							  List<ErrorMessage> errorMessageList,
							  Map<String, SysBaseSetInfo> socialBaseSetMap,
							  Map<String, SysBaseSetInfo> fundBaseSetMap,
							  Map<String,SysUser> userMap,
							  Map<String,String> existMap) {
		// 执行数据插入操作 组装
		TSocialfundHouseRes save;
		SysUser user;
		R<SysUser> res;
		TSocialfundHouseRes exist;
		String temp;
		SysBaseSetInfo baseSet = null;
		for (int i = 0; i < excelVOList.size(); i++) {
			SocialAuthImportVo excel = excelVOList.get(i);
			// 数据合法情况
			user = userMap.get(excel.getUserLoginName());
			// 用户信息验证
			if (Common.isEmpty(user)){
				res = upmsDaprUtils.getSimpleUserByLoginName(excel.getUserLoginName());
				if (Common.isNotNull(res) && Common.isNotNull(res.getData())){
					user = res.getData();
					userMap.put(user.getUsername(),user);
				}else {
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(),"无有效状态的用户信息！",excel));
					continue;
				}
			}
			if (Common.isEmpty(user.getDeptName())){
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(),"对应登录账号无部门信息，请完善后导入",excel));
				continue;
			}
			// 户验证
			if (CommonConstants.ZERO_STRING.equals(excel.getType())){
				baseSet = socialBaseSetMap.get(excel.getHouseHold());
				if (Common.isEmpty(baseSet)){
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(),"未找到对应社保户数据！",excel));
					continue;
				}
			}
			if (CommonConstants.ONE_STRING.equals(excel.getType())){
				baseSet = fundBaseSetMap.get(excel.getHouseHold());
				if (Common.isEmpty(baseSet)){
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(),"未找到对应公积金户数据！",excel));
					continue;
				}
			}
			// 重复校验
			temp = existMap.get(excel.getUserLoginName()
					+CommonConstants.DOWN_LINE_STRING
					+excel.getHouseHold()
					+CommonConstants.DOWN_LINE_STRING
					+ excel.getType());
			if (Common.isNotNull(temp)){
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(),"对应账号的权限已存在，请勿重复导入",excel));
				continue;
			}else {
				if (CommonConstants.ZERO_STRING.equals(excel.getType())){
					exist = baseMapper.selectOne(Wrappers.<TSocialfundHouseRes>query().lambda()
							.eq(TSocialfundHouseRes::getSocialHousehold,excel.getHouseHold())
							.eq(TSocialfundHouseRes::getHouseNameType,excel.getType())
							.eq(TSocialfundHouseRes::getUserId,user.getUserId())
							.eq(TSocialfundHouseRes::getAuthType,CommonConstants.ZERO_STRING)
							.last(CommonConstants.LAST_ONE_SQL));
				}else {
					exist = baseMapper.selectOne(Wrappers.<TSocialfundHouseRes>query().lambda()
							.eq(TSocialfundHouseRes::getFundHousehold,excel.getHouseHold())
							.eq(TSocialfundHouseRes::getHouseNameType,excel.getType())
							.eq(TSocialfundHouseRes::getUserId,user.getUserId())
							.eq(TSocialfundHouseRes::getAuthType,CommonConstants.ZERO_STRING)
							.last(CommonConstants.LAST_ONE_SQL));
				}

				if (Common.isNotNull(exist)){
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(),"对应账号的权限已存在，请勿重复导入",excel));
					continue;
				}
			}
			// 初始化及新增数据
			save = new TSocialfundHouseRes();
			save.setAuthType(CommonConstants.ZERO_STRING);
			save.setFundHousehold(CommonConstants.ZERO_STRING.equals(baseSet.getBaseType())?null:baseSet.getDepartName());
			save.setSocialHousehold(CommonConstants.ZERO_STRING.equals(baseSet.getBaseType())?baseSet.getDepartName():null);
			save.setStatus(CommonConstants.ZERO_STRING);
			save.setUserId(user.getUserId());
			save.setHouseNameType(baseSet.getBaseType());
			save.setCreateTime(LocalDateTime.now());
			save.setUserName(user.getNickname());
			save.setUserDeptName(user.getDeptName());
			insertExcel(save);
			// 加入map 验证当前表单数据是否重复
			existMap.put(excel.getUserLoginName()
					+CommonConstants.DOWN_LINE_STRING
					+excel.getHouseHold()
					+CommonConstants.DOWN_LINE_STRING
					+ excel.getType(),excel.getHouseHold());
			errorMessageList.add(new ErrorMessage(excel.getRowIndex(),CommonConstants.SAVE_SUCCESS,CommonConstants.GREEN,excel));
		}
	}
	/**
	 * 插入excel bad record
	 */
	private void insertExcel(TSocialfundHouseRes entity) {
		this.save(entity);
	}
	/**
	 * @Author fxj
	 * @Description 判断所有返回数据，是否全部为正确的
	 * @Date 18:01 2023/10/18
	 * @Param
	 * @return
	**/
	private R<List<ErrorMessage>> judgeAllMessage(List<ErrorMessage> errorMessageList) {
		if (!errorMessageList.isEmpty() && errorMessageList.stream().noneMatch(e-> e.getColor().equals(CommonConstants.RED))) {
			return R.ok();
		}
		return R.ok(errorMessageList);
	}

	/**
	 * @Author fxj
	 * @Description 批量新增社保公积金审核权限
	 * @Date 16:59 2023/10/17
	 * @Param
	 * @return
	 **/
	@Transactional(rollbackFor = Exception.class)
	@ShardingTransactionType(TransactionType.BASE)
	@Override
	public R<List<ErrorMessage>> importDiyAll(InputStream inputStream,String type) {
		List<ErrorMessage> errorMessageList = new ArrayList<>();
		ExcelUtil<SocialAuthHandleImportVo> util1 = new ExcelUtil<>(SocialAuthHandleImportVo.class);
		Map<String, SysBaseSetInfo> baseSetInfoMap= new HashMap<>();
		List<SysBaseSetInfo>  setInfos = baseSetInfoService.list(Wrappers.<SysBaseSetInfo>query().lambda()
				.eq(SysBaseSetInfo::getBaseType,type)
				.eq(SysBaseSetInfo::getDeleteFlag,CommonConstants.ZERO_STRING)
				.eq(SysBaseSetInfo::getStatus,CommonConstants.ZERO_STRING)
				.groupBy(SysBaseSetInfo::getDepartName,SysBaseSetInfo::getProvince,SysBaseSetInfo::getCity,SysBaseSetInfo::getTown));
		if (Common.isNotNull(setInfos)){
			baseSetInfoMap = setInfos.stream().collect(Collectors.toMap(k->k.getDepartName(),k->k));
		}
		if (Common.isEmpty(baseSetInfoMap)){
			return R.failed("获取户配置信息失败！");
		}
		Map<String, SysUser> userMap = new HashMap<>();
		Map<String,String> existMap = new HashMap<>();
		// 写法2：
		// 匿名内部类 不用额外写一个DemoDataListener
		// 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
		try {
			Map<String, SysBaseSetInfo> finalBaseSetInfoMap = baseSetInfoMap;
			EasyExcel.read(inputStream, SocialAuthHandleImportVo.class, new ReadListener<SocialAuthHandleImportVo>() {
				/**
				 * 单次缓存的数据量
				 */
				public static final int BATCH_COUNT = CommonConstants.BATCH_COUNT;
				/**
				 *临时存储
				 */
				private List<SocialAuthHandleImportVo> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

				@Override
				public void invoke(SocialAuthHandleImportVo data, AnalysisContext context) {
					ReadRowHolder readRowHolder = context.readRowHolder();
					Integer rowIndex = readRowHolder.getRowIndex();
					data.setRowIndex(rowIndex+1);
					ErrorMessage errorMessage = util1.checkEntity(data, data.getRowIndex());
					if (Common.isNotNull(errorMessage)){
						errorMessage.setData(data);
						errorMessageList.add(errorMessage);
					}else {
						cachedDataList.add(data);
					}
					if (cachedDataList.size() >= BATCH_COUNT) {
						saveData();
						// 存储完成清理 list
						cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
					}
				}
				@Override
				public void doAfterAllAnalysed(AnalysisContext context) {
					saveData();
				}

				/**
				 * 加上存储数据库
				 */
				private void saveData() {
					log.info("{}条数据，开始存储数据库！", cachedDataList.size());
					importEntity(cachedDataList,errorMessageList, finalBaseSetInfoMap,userMap,existMap,type);
					log.info("存储数据库成功！");
				}
			}).sheet().doRead();
		}catch (Exception e){
			log.error(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR,e);
			return R.failed(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR);
		}finally {
			// 清理
			baseSetInfoMap.clear();
		}
		return  judgeAllMessage(errorMessageList);
	}

	private void importEntity(List<SocialAuthHandleImportVo> excelVOList,
							  List<ErrorMessage> errorMessageList,
							  Map<String, SysBaseSetInfo> baseSetInfoMap,
							  Map<String,SysUser> userMap,
							  Map<String,String> existMap,
							  String type) {
		// 执行数据插入操作 组装
		TSocialfundHouseRes save;
		SysUser user;
		R<SysUser> res;
		TSocialfundHouseRes exist;
		String temp;
		SysBaseSetInfo baseSet = null;
		for (int i = 0; i < excelVOList.size(); i++) {
			SocialAuthHandleImportVo excel = excelVOList.get(i);
			// 数据合法情况
			user = userMap.get(excel.getUserLoginName());
			// 用户信息验证
			if (Common.isEmpty(user)){
				res = upmsDaprUtils.getSimpleUserByLoginName(excel.getUserLoginName());
				if (Common.isNotNull(res) && Common.isNotNull(res.getData())){
					user = res.getData();
					userMap.put(user.getUsername(),user);
				}else {
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(),"无有效状态的用户信息！",excel));
					continue;
				}
			}
			if (Common.isEmpty(user.getDeptName())){
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(),"对应登录账号无部门信息，请完善后导入",excel));
				continue;
			}
			// 户验证
			if (CommonConstants.ZERO_STRING.equals(type)){
				baseSet = baseSetInfoMap.get(excel.getHouseHold());
				if (Common.isEmpty(baseSet)){
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(),"未找到对应社保户数据！",excel));
					continue;
				}
			}
			if (CommonConstants.ONE_STRING.equals(type)){
				baseSet = baseSetInfoMap.get(excel.getHouseHold());
				if (Common.isEmpty(baseSet)){
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(),"未找到对应公积金户数据！",excel));
					continue;
				}
			}
			// 重复校验
			temp = existMap.get(excel.getUserLoginName()
					+CommonConstants.DOWN_LINE_STRING
					+excel.getHouseHold());
			if (Common.isNotNull(temp)){
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(),"对应账号的权限已存在，请勿重复导入",excel));
				continue;
			}else {
				if (CommonConstants.ZERO_STRING.equals(type)){
					exist = baseMapper.selectOne(Wrappers.<TSocialfundHouseRes>query().lambda()
							.eq(TSocialfundHouseRes::getSocialHousehold,excel.getHouseHold())
							.eq(TSocialfundHouseRes::getUserId,user.getUserId())
							.eq(TSocialfundHouseRes::getHouseNameType,type)
							.eq(TSocialfundHouseRes::getAuthType,CommonConstants.ONE_STRING)
							.last(CommonConstants.LAST_ONE_SQL));
				}else {
					exist = baseMapper.selectOne(Wrappers.<TSocialfundHouseRes>query().lambda()
							.eq(TSocialfundHouseRes::getFundHousehold,excel.getHouseHold())
							.eq(TSocialfundHouseRes::getUserId,user.getUserId())
							.eq(TSocialfundHouseRes::getHouseNameType,type)
							.eq(TSocialfundHouseRes::getAuthType,CommonConstants.ONE_STRING)
							.last(CommonConstants.LAST_ONE_SQL));
				}
				if (Common.isNotNull(exist)){
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(),"对应账号的权限已存在，请勿重复导入",excel));
					continue;
				}
			}
			// 初始化及新增数据
			save = new TSocialfundHouseRes();
			save.setAuthType(CommonConstants.ONE_STRING);
			save.setFundHousehold(CommonConstants.ZERO_STRING.equals(type)?null:baseSet.getDepartName());
			save.setSocialHousehold(CommonConstants.ZERO_STRING.equals(type)?baseSet.getDepartName():null);
			save.setStatus(CommonConstants.ZERO_STRING);
			save.setUserId(user.getUserId());
			save.setHouseNameType(type);
			save.setCreateTime(LocalDateTime.now());
			save.setUserName(user.getNickname());
			save.setUserDeptName(user.getDeptName());
			insertExcel(save);
			// 加入map 验证当前表单数据是否重复
			existMap.put(excel.getUserLoginName()
					+CommonConstants.DOWN_LINE_STRING
					+excel.getHouseHold(),excel.getUserLoginName());
			errorMessageList.add(new ErrorMessage(excel.getRowIndex(),CommonConstants.SAVE_SUCCESS,CommonConstants.GREEN,excel));
		}
	}

	/**
	 * @Description: 获取登录人的社保办理权限
	 * @Author: hgw
	 * @Date: 2025/6/16 11:31
	 * @return: java.util.Map<java.lang.String, java.lang.Integer>
	 **/
	@Override
	public Map<String, Integer> getMapByHandleUser(String userId) {
		Map<String, Integer> map = new HashMap<>();
		if (Common.isNotNull(userId)){
			List<String> socialList = baseMapper.getSocialListByUserId(userId);
			if (Common.isNotNull(socialList)){
				for (String social : socialList) {
					map.put(social, CommonConstants.ONE_INT);
				}
			}
		}
		return map;
	}

}
