/*
 *    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.ExcelWriter;
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.alibaba.excel.write.metadata.WriteSheet;
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.check.entity.TCheckMobile;
import com.yifu.cloud.plus.v1.yifu.admin.api.entity.SysArea;
import com.yifu.cloud.plus.v1.yifu.admin.api.entity.SysUser;
import com.yifu.cloud.plus.v1.yifu.admin.api.vo.AllUserNaVo;
import com.yifu.cloud.plus.v1.yifu.admin.api.vo.AreaVo;
import com.yifu.cloud.plus.v1.yifu.admin.api.vo.KeyValueReturnVo;
import com.yifu.cloud.plus.v1.yifu.admin.api.vo.ListAndStringVo;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CacheConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.SecurityConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.*;
import com.yifu.cloud.plus.v1.yifu.common.dapr.config.DaprCheckProperties;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.HttpDaprUtil;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.UpmsDaprUtils;
import com.yifu.cloud.plus.v1.yifu.insurances.util.BeanCopyUtils;
import com.yifu.cloud.plus.v1.yifu.social.constants.HouseConfigConstants;
import com.yifu.cloud.plus.v1.yifu.social.entity.*;
import com.yifu.cloud.plus.v1.yifu.social.mapper.SysBaseSetInfoMapper;
import com.yifu.cloud.plus.v1.yifu.social.mapper.SysHouseHoldInfoMapper;
import com.yifu.cloud.plus.v1.yifu.social.service.*;
import com.yifu.cloud.plus.v1.yifu.social.vo.TSocialHouseholdExportVo;
import com.yifu.cloud.plus.v1.yifu.social.vo.TSocialHouseholdInsertVo;
import com.yifu.cloud.plus.v1.yifu.social.vo.TSocialHouseholdUpdateVo;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 社保户公积金户数据
 *
 * @author fxj
 * @date 2022-07-12 08:53:19
 */
@Service
@RequiredArgsConstructor
@EnableConfigurationProperties(DaprCheckProperties.class)
public class SysHouseHoldInfoServiceImpl extends ServiceImpl<SysHouseHoldInfoMapper, SysHouseHoldInfo> implements SysHouseHoldInfoService {

	private final SysBaseSetInfoMapper baseSetInfoMapper;

	@Autowired
	private TSocialfundHouseResService tSocialfundHouseResService;

	private final TAttaInfoService attaInfoService;

	@Autowired
	private DaprCheckProperties daprCheckProperties;
	@Autowired
	private SysHouseHoldInfoFailResService sysHouseHoldInfoFailResService;
	@Autowired
	private FailReasonConfigService failReasonConfigService;

	@Autowired
	private UpmsDaprUtils upmsDaprUtils;

	@Autowired
	private OSSUtil ossUtil;

    /**
     * 社保户公积金户数据简单分页查询
     * @param sysHouseHoldInfo 社保户公积金户数据
     * @return
     */
    @Override
    public IPage<SysHouseHoldInfo> getSysHouseHoldInfoPage(Page<SysHouseHoldInfo> page, SysHouseHoldInfo sysHouseHoldInfo){
        return baseMapper.getSysHouseHoldInfoPage(page,sysHouseHoldInfo);
    }

	/**
	 * 获取所有的独立户数据
	 * @param page
	 * @return
	 */
	@Override
	public IPage<SysHouseHoldInfo> getAllSingleSocailPage(Page<SysHouseHoldInfo> page){
		return baseMapper.getAllSingleSocailPage(page);
	}

	/**
	 * 户新增
	 * @param sysHouseHoldInfo 社保户公积金户数据
	 * @return
	 */
	@Override
	public R<Boolean> saveInfo(SysHouseHoldInfo sysHouseHoldInfo) {
		//户名称去空格
		sysHouseHoldInfo.setName(sysHouseHoldInfo.getName().replace(" ",""));
		SysHouseHoldInfo info = this.getOne(Wrappers.<SysHouseHoldInfo>query().lambda()
					.eq(SysHouseHoldInfo::getType,sysHouseHoldInfo.getType())
					.eq(SysHouseHoldInfo::getName,sysHouseHoldInfo.getName())
					.last(CommonConstants.LAST_ONE_SQL));
		if (null != info){
			return R.failed("对应账户性质、户名的配置已存在！");
		}
		if (Common.isEmpty(sysHouseHoldInfo.getAuditUser()) || Common.isEmpty(sysHouseHoldInfo.getHandleUser())) {
			return R.failed("审核人或办理人必填！");
		}
		// 判断审核人与办理人的权限：
		String judgeAuth = this.judgeAuditAndHandleAuth(sysHouseHoldInfo.getType()
				, sysHouseHoldInfo.getAuditUser(), sysHouseHoldInfo.getAuditUserName()
				, sysHouseHoldInfo.getHandleUser(), sysHouseHoldInfo.getHandleUserName());
		if (Common.isNotNull(judgeAuth)) {
			return R.failed(judgeAuth);
		}
		//获取行政区化代码
		if (CommonConstants.ZERO_STRING.equals(sysHouseHoldInfo.getType())) {
			HashMap<String, SysArea> map = initAreaMap();
			if (Common.isNotNull(map) && map.size() > 0) {
				SysArea area = map.get(sysHouseHoldInfo.getCity());
				if (Common.isNotNull(area)) {
					sysHouseHoldInfo.setAreaCode(area.getAreaCode());
				}
			}
		}
		List<SysHouseHoldInfoFailRes> resList = sysHouseHoldInfo.getResList();
		// 先判断
		if (Common.isNotNull(resList) && !resList.isEmpty()) {
			R<Boolean> failed = judgeHuAndResStatus(sysHouseHoldInfo, resList);
			if (failed != null) { return failed;}
		}
		baseMapper.insert(sysHouseHoldInfo);
		// 后保存
		if (Common.isNotNull(resList) && !resList.isEmpty()) {
			for (SysHouseHoldInfoFailRes res : resList) {
				res.setId(sysHouseHoldInfo.getId());
			}
			sysHouseHoldInfoFailResService.saveBatch(resList);
		}
		//维护附件信息
		TAttaInfo attaInfo = null;
		if (Common.isNotNull(sysHouseHoldInfo.getAttaId())) {
			attaInfo = attaInfoService.getById(sysHouseHoldInfo.getAttaId());
			if (null != attaInfo){
				attaInfo.setDomainId(sysHouseHoldInfo.getId());
				attaInfoService.updateById(attaInfo);
			}
		}
		// 11社保增花名册模板；12社保减花名册模板；13医保增花名册模板；14医保减花名册模板
		if (Common.isNotNull(sysHouseHoldInfo.getAddRosterTempYgs())) {
			attaInfo = attaInfoService.getById(sysHouseHoldInfo.getAddRosterTempYgs());
			if (null != attaInfo){
				attaInfo.setDomainId(sysHouseHoldInfo.getId());
				attaInfo.setRelationType("11");
				attaInfoService.updateById(attaInfo);
			}
		}
		if (Common.isNotNull(sysHouseHoldInfo.getReduceRosterTempYgs())) {
			attaInfo = attaInfoService.getById(sysHouseHoldInfo.getReduceRosterTempYgs());
			if (null != attaInfo){
				attaInfo.setDomainId(sysHouseHoldInfo.getId());
				attaInfo.setRelationType("12");
				attaInfoService.updateById(attaInfo);
			}
		}
		if (Common.isNotNull(sysHouseHoldInfo.getAddRosterTempYsd())) {
			attaInfo = attaInfoService.getById(sysHouseHoldInfo.getAddRosterTempYsd());
			if (null != attaInfo){
				attaInfo.setDomainId(sysHouseHoldInfo.getId());
				attaInfo.setRelationType("13");
				attaInfoService.updateById(attaInfo);
			}
		}
		if (Common.isNotNull(sysHouseHoldInfo.getReduceRosterTempYsd())) {
			attaInfo = attaInfoService.getById(sysHouseHoldInfo.getReduceRosterTempYsd());
			if (null != attaInfo){
				attaInfo.setDomainId(sysHouseHoldInfo.getId());
				attaInfo.setRelationType("14");
				attaInfoService.updateById(attaInfo);
			}
		}
		// 同步审核权限、办理权限
		this.saveAuditUserOrHandleUser(sysHouseHoldInfo, CommonConstants.ZERO_STRING);
		this.saveAuditUserOrHandleUser(sysHouseHoldInfo, CommonConstants.ONE_STRING);
		return R.ok();
	}

	/**
	 * @param type 账户性质：0社保 1公积金
	 * @param auditUser 审核人ID
	 * @param handleUser 办理人ID
	 * @Description: 判断审核人与办理人的菜单权限是否已配置
	 * @Author: hgw
	 * @Date: 2025/9/4 16:03
	 * @return: java.lang.String
	 **/
	private String judgeAuditAndHandleAuth(String type, String auditUser, String auditUserName, String handleUser, String handleUserName) {

		String returnStr = "";
		String valueStr;
		String typeName = "社保";
		if (CommonConstants.ONE_STRING.equals(type)) {
			typeName = "公积金";
		}
		String auditNoPrf = "审核人（"+auditUserName+"）账号";
		String auditNo = auditNoPrf + "没有派单审核角色，";
		List<String> userIdList = new ArrayList<>();

		String menuId;
		ListAndStringVo paramVo = new ListAndStringVo();
		R<KeyValueReturnVo> returnVoR;
		// 1审核人：
		if (Common.isNotNull(auditUser)) {
			userIdList.add(auditUser);
			// 【角色】的【派单审核】菜单
			menuId = "1549677464986763265";
			paramVo.setIdList(userIdList);
			paramVo.setIdString(menuId);
			returnVoR = upmsDaprUtils.judgeMenuByUserIdAndMenuId(paramVo);
			if (returnVoR != null && returnVoR.getData() != null && returnVoR.getData().getKeyValueMap() != null && !returnVoR.getData().getKeyValueMap().isEmpty()) {
				valueStr = returnVoR.getData().getKeyValueMap().get(auditUser);
				if (Common.isEmpty(valueStr) || CommonConstants.ZERO_STRING.equals(valueStr)) {
					returnStr = auditNo;
				}
			} else {
				returnStr = auditNo;
			}

			if (Common.isEmpty(returnStr)) {
				auditNo = auditNoPrf + "没有派单审核用户组权限，";
			} else {
				auditNo = "没有派单审核用户组权限，";
			}

			// 【数据权限】的【派单审核】菜单
			menuId = "1549677464986763265";
			paramVo = new ListAndStringVo();
			paramVo.setIdList(userIdList);
			paramVo.setIdString(menuId);
			returnVoR = upmsDaprUtils.judgeDiyAuthMenuByUserId(paramVo);
			if (returnVoR != null && returnVoR.getData() != null && returnVoR.getData().getKeyValueMap() != null && !returnVoR.getData().getKeyValueMap().isEmpty()) {
				valueStr = returnVoR.getData().getKeyValueMap().get(auditUser);
				if (Common.isEmpty(valueStr) || CommonConstants.ZERO_STRING.equals(valueStr)) {
					returnStr += auditNo;
				}
			} else {
				returnStr += auditNo;
			}
			if (Common.isNotNull(returnStr)) {
				returnStr += "不能授权为审核人。";
			}
		}

		String returnStrHandle = "";
		// 2办理人
		if (Common.isNotNull(handleUser)) {
			String handleNoPrf = "办理人（" + handleUserName + "）账号";
			String handleNo = handleNoPrf + "没有" + typeName + "的办理角色，";

			// 1：角色菜单
			// 社保、公积金办理，换成用办理人查询：
			userIdList = new ArrayList<>();
			userIdList.add(handleUser);
			// 社保办理
			if (CommonConstants.ZERO_STRING.equals(type)) {
				menuId = "1549678343483736066";
				paramVo = new ListAndStringVo();
				paramVo.setIdList(userIdList);
				paramVo.setIdString(menuId);
				returnVoR = upmsDaprUtils.judgeMenuByUserIdAndMenuId(paramVo);
				if (returnVoR != null && returnVoR.getData() != null && returnVoR.getData().getKeyValueMap() != null && !returnVoR.getData().getKeyValueMap().isEmpty()) {
					valueStr = returnVoR.getData().getKeyValueMap().get(handleUser);
					if (Common.isEmpty(valueStr) || CommonConstants.ZERO_STRING.equals(valueStr)) {
						returnStrHandle += handleNo;
					}
				} else {
					returnStrHandle += handleNo;
				}
			}
			// 公积金办理
			if (CommonConstants.ONE_STRING.equals(type)) {
				menuId = "1549678424018567170";
				paramVo = new ListAndStringVo();
				paramVo.setIdList(userIdList);
				paramVo.setIdString(menuId);
				returnVoR = upmsDaprUtils.judgeMenuByUserIdAndMenuId(paramVo);
				if (returnVoR != null && returnVoR.getData() != null && returnVoR.getData().getKeyValueMap() != null && !returnVoR.getData().getKeyValueMap().isEmpty()) {
					valueStr = returnVoR.getData().getKeyValueMap().get(handleUser);
					if (Common.isEmpty(valueStr) || CommonConstants.ZERO_STRING.equals(valueStr)) {
						returnStrHandle += handleNo;
					}
				} else {
					returnStrHandle += handleNo;
				}
			}

			if (Common.isEmpty(returnStrHandle)) {
				handleNo = handleNoPrf + "没有" + typeName + "的用户组权限，";
			} else {
				handleNo = "没有" + typeName + "的用户组权限，";
			}

			// 社保、公积金办理，换成用办理人查询：
			userIdList = new ArrayList<>();
			userIdList.add(handleUser);
			// 社保办理
			if (CommonConstants.ZERO_STRING.equals(type)) {
				menuId = "1549678343483736066";
				paramVo = new ListAndStringVo();
				paramVo.setIdList(userIdList);
				paramVo.setIdString(menuId);
				returnVoR = upmsDaprUtils.judgeDiyAuthMenuByUserId(paramVo);
				if (returnVoR != null && returnVoR.getData() != null && returnVoR.getData().getKeyValueMap() != null && !returnVoR.getData().getKeyValueMap().isEmpty()) {
					valueStr = returnVoR.getData().getKeyValueMap().get(handleUser);
					if (Common.isEmpty(valueStr) || CommonConstants.ZERO_STRING.equals(valueStr)) {
						returnStrHandle += handleNo;
					}
				} else {
					returnStrHandle += handleNo;
				}
			}
			// 公积金办理
			if (CommonConstants.ONE_STRING.equals(type)) {
				menuId = "1549678424018567170";
				paramVo = new ListAndStringVo();
				paramVo.setIdList(userIdList);
				paramVo.setIdString(menuId);
				returnVoR = upmsDaprUtils.judgeDiyAuthMenuByUserId(paramVo);
				if (returnVoR != null && returnVoR.getData() != null && returnVoR.getData().getKeyValueMap() != null && !returnVoR.getData().getKeyValueMap().isEmpty()) {
					valueStr = returnVoR.getData().getKeyValueMap().get(handleUser);
					if (Common.isEmpty(valueStr) || CommonConstants.ZERO_STRING.equals(valueStr)) {
						returnStrHandle += handleNo;
					}
				} else {
					returnStrHandle += handleNo;
				}
			}

			if (Common.isNotNull(returnStrHandle)) {
				returnStrHandle += "不能授权为办理人。";
			}
		}

		if (Common.isNotNull(returnStr) || Common.isNotNull(returnStrHandle)) {
			returnStr += returnStrHandle + "请找管理员协助补足权限后重新授权。";
		}
		return returnStr;
	}

	/**
	 * 查询
	 * @param id
	 * @return
	 */
	@Override
	public R<SysHouseHoldInfo> getByIdAtta(String id) {
		SysHouseHoldInfo sysHouseHoldInfo = baseMapper.selectById(id);
		if (null == sysHouseHoldInfo){
			return R.failed(CommonConstants.PARAM_INFO_ERROR);
		}
		List<TAttaInfo> attaInfos = attaInfoService.list(Wrappers.<TAttaInfo>query().lambda().eq(TAttaInfo::getDomainId, id));
		if (Common.isNotNull(attaInfos)) {
			URL url;
			List<TAttaInfo> attaList = new ArrayList<>();
			for (TAttaInfo attaInfo: attaInfos){
				url = ossUtil.getObjectUrl(null, attaInfo.getAttaSrc());
				if (Common.isNotNull(url)) {
					attaInfo.setAttaUrl(url.toString());
				}
				if (CommonConstants.ONE_STRING.equals(attaInfo.getRelationType())){
					sysHouseHoldInfo.setAtta(attaInfo);
				}else {
					attaList.add(attaInfo);
				}
			}
			sysHouseHoldInfo.setTempAttas(attaList);
		}
		return R.ok(sysHouseHoldInfo);
	}

	/**
	 * @param authType 0 审核人 1办理人
	 * @Description: 添加审核人、办理人
	 * @Author: hgw
	 * @Date: 2022/12/6 15:50
	 * @return: void
	 **/
	private void saveAuditUserOrHandleUser(SysHouseHoldInfo sysHouseHoldInfo, String authType) {
		TSocialfundHouseRes searchVo = new TSocialfundHouseRes();
		searchVo.setAuthType(authType);
		searchVo.setHouseNameType(sysHouseHoldInfo.getType());
		if (CommonConstants.ZERO_STRING.equals(sysHouseHoldInfo.getType())) {
			searchVo.setSocialHousehold(sysHouseHoldInfo.getName());
		} else {
			searchVo.setFundHousehold(sysHouseHoldInfo.getName());
		}
		if (CommonConstants.ZERO_STRING.equals(authType)) {
			searchVo.setUserId(sysHouseHoldInfo.getAuditUser());
			searchVo.setUserName(sysHouseHoldInfo.getAuditUserName());
			searchVo.setUserDeptName(sysHouseHoldInfo.getAuditUserDeptName());
		} else {
			searchVo.setUserId(sysHouseHoldInfo.getHandleUser());
			searchVo.setUserName(sysHouseHoldInfo.getHandleUserName());
			searchVo.setUserDeptName(sysHouseHoldInfo.getHandleUserDeptName());
		}
		tSocialfundHouseResService.saveSocialAuth(searchVo);
	}

	/**
	 * @Author fxj
	 * @Description 修改社保户公积金户数据
	 * @Date 16:08 2022/11/14
	**/
	@Override
	public R<Boolean> updateByIdAsso(SysHouseHoldInfo hold) {
		//户名称去空格
		//1.9.3版本处理线上空指针问题修改，增加户名判空
		if (Common.isNotNull(hold.getName())) {
			hold.setName(hold.getName().replace(" ", ""));
		}
		if (Common.isEmpty(hold.getId())){
			return  R.failed(CommonConstants.PARAM_INFO_ERROR);
		}
		SysHouseHoldInfo holdInfo = baseMapper.selectById(hold.getId());
		if (Common.isEmpty(holdInfo)){
			return R.failed(CommonConstants.NO_DATA_TO_HANDLE);
		}
		// 编辑标志 true：编辑；false：启用禁用（说明不需要拦截其他必填项）
		boolean isEdit = true;
		if (Common.isEmpty(hold.getType()) && Common.isNotNull(hold.getDelFlag())) {
			isEdit = false;
		}
		if (isEdit && (Common.isEmpty(hold.getAuditUser()) || Common.isEmpty(hold.getHandleUser()))) {
			return R.failed("审核人或办理人必填！");
		}
		if (isEdit) {
			// 判断审核人与办理人的权限：
			String judgeAuth = this.judgeAuditAndHandleAuth(hold.getType()
					, hold.getAuditUser(), hold.getAuditUserName()
					, hold.getHandleUser(), hold.getHandleUserName());
			if (Common.isNotNull(judgeAuth)) {
				return R.failed(judgeAuth);
			}
		}
		if (CommonConstants.ONE_STRING.equals(hold.getDelFlag())
				&& baseSetInfoMapper.selectCount(Wrappers.<SysBaseSetInfo>query().lambda()
				.eq(SysBaseSetInfo::getBaseType, holdInfo.getType())
				.le(SysBaseSetInfo::getApplyStartDate, DateUtil.getCurrentDateTime())
				.in(SysBaseSetInfo::getDepartId,holdInfo.getId())
				.eq(SysBaseSetInfo::getStatus,CommonConstants.ZERO_STRING)
				.eq(SysBaseSetInfo::getDeleteFlag, CommonConstants.ZERO_STRING)
				.and(obj-> obj.isNull(SysBaseSetInfo::getApplyEndDate).or()
						.ge(SysBaseSetInfo::getApplyEndDate,DateUtil.getCurrentDateTime()))) > CommonConstants.ZERO_INT){
			return R.failed("户下存在可用基数配置，请禁用可用基数配置后禁用户配置！");
		}
		//更新行政区划代码
		if (CommonConstants.ZERO_STRING.equals(hold.getType()) && Common.isNotNull(hold.getCity())) {
			HashMap<String, SysArea> map = initAreaMap();
			if (Common.isNotNull(map) && map.size() > 0) {
				SysArea area = map.get(hold.getCity());
				if (Common.isNotNull(area)) {
					hold.setAreaCode(area.getAreaCode());
				}
			}
		}
		if (isEdit) {
			List<SysHouseHoldInfoFailRes> resList = hold.getResList();
			if (Common.isNotNull(resList) && !resList.isEmpty()) {
				R<Boolean> failed = judgeHuAndResStatus(hold, resList);
				if (failed != null) { return failed;}
				sysHouseHoldInfoFailResService.removeById(hold.getId());
				sysHouseHoldInfoFailResService.saveBatch(resList);
			} else {
				sysHouseHoldInfoFailResService.removeById(hold.getId());
			}
		}
		int res = baseMapper.updateById(hold);
		if (res >= 0){
			if (isEdit) {
				// 新老数据审核人办理人不同，先删除，再添加
				if (Common.isNotNull(holdInfo.getAuditUser()) && !holdInfo.getAuditUser().equals(hold.getAuditUser())) {
					tSocialfundHouseResService.deleteAuditUser(holdInfo);
				}
				if (Common.isNotNull(holdInfo.getHandleUser()) && !holdInfo.getHandleUser().equals(hold.getHandleUser())) {
					tSocialfundHouseResService.deleteHandleUser(holdInfo);
				}
				// 同步审核权限、办理权限
				this.saveAuditUserOrHandleUser(hold, CommonConstants.ZERO_STRING);
				this.saveAuditUserOrHandleUser(hold, CommonConstants.ONE_STRING);
			}
			return  R.ok();
		}else {
			return R.failed(CommonConstants.SAVE_FAILED);
		}
	}

	private R<Boolean> judgeHuAndResStatus(SysHouseHoldInfo hold, List<SysHouseHoldInfoFailRes> resList) {
		FailReasonConfig s;
		String failKey = "";
		for (SysHouseHoldInfoFailRes res : resList) {
			if (Common.isEmpty(res.getFailId())) {
				return R.failed("【失败原因ID】必填！");
			}
			if (Common.isEmpty(res.getReplay())) {
				return R.failed("【处理方式】必填！");
			}
			res.setId(hold.getId());
			s = failReasonConfigService.getById(res.getFailId());
			if (s == null || Common.isEmpty(s.getId())) {
				return R.failed("【根据失败原因ID，未找到失败原因】！");
			} else if (CommonConstants.ONE_STRING.equals(s.getStatus())) {
				failKey += s.getReasonKey() + ";";
			}
		}
		if (Common.isNotNull(failKey)) {
			return R.failed(failKey + " 已被禁用，请更换！");
		}
		return null;
	}

	@Override
	public R<List<ErrorMessage>> importListAdd(InputStream inputStream) {
		List<ErrorMessage> errorMessageList = new ArrayList<>();
		ExcelUtil<TSocialHouseholdInsertVo> util1 = new ExcelUtil<>(TSocialHouseholdInsertVo.class);
		// 写法2：
		// 匿名内部类 不用额外写一个DemoDataListener
		// 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
		try {
			EasyExcel.read(inputStream, TSocialHouseholdInsertVo.class, new ReadListener<TSocialHouseholdInsertVo>() {
				/**
				 * 单次缓存的数据量
				 */
				public static final int BATCH_COUNT = CommonConstants.BATCH_COUNT;
				/**
				 *临时存储
				 */
				private List<TSocialHouseholdInsertVo> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

				@Override
				public void invoke(TSocialHouseholdInsertVo data, AnalysisContext context) {
					ReadRowHolder readRowHolder = context.readRowHolder();
					Integer rowIndex = readRowHolder.getRowIndex();
					data.setRowIndex(rowIndex+1);
					TSocialHouseholdInsertVo dataReturn = new TSocialHouseholdInsertVo();
					BeanCopyUtils.copyProperties(data,dataReturn);
					ErrorMessage errorMessage = util1.checkEntity(data, data.getRowIndex());
					if (Common.isNotNull(errorMessage)){
						errorMessage.setData(dataReturn);
						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() {
					importSocialHouseInsert(cachedDataList,errorMessageList);
				}
			}).sheet().doRead();
		}catch (Exception e){
			log.error(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR,e);
			return R.failed(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR);
		}
		if (errorMessageList.stream().allMatch(e->e.getMessage().equals(CommonConstants.SAVE_SUCCESS))) {
			return R.ok();
		} else {
			return R.ok(errorMessageList);
		}
	}

	@Override
	public R<List<ErrorMessage>> importListUpdate(InputStream inputStream) {
		List<ErrorMessage> errorMessageList = new ArrayList<>();
		ExcelUtil<TSocialHouseholdUpdateVo> util1 = new ExcelUtil<>(TSocialHouseholdUpdateVo.class);
		// 写法2：
		// 匿名内部类 不用额外写一个DemoDataListener
		// 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
		try {
			EasyExcel.read(inputStream, TSocialHouseholdUpdateVo.class, new ReadListener<TSocialHouseholdUpdateVo>() {
				/**
				 * 单次缓存的数据量
				 */
				public static final int BATCH_COUNT = CommonConstants.BATCH_COUNT;
				/**
				 *临时存储
				 */
				private List<TSocialHouseholdUpdateVo> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

				@Override
				public void invoke(TSocialHouseholdUpdateVo data, AnalysisContext context) {
					ReadRowHolder readRowHolder = context.readRowHolder();
					Integer rowIndex = readRowHolder.getRowIndex();
					data.setRowIndex(rowIndex+1);
					TSocialHouseholdInsertVo dataReturn = new TSocialHouseholdInsertVo();
					BeanCopyUtils.copyProperties(data,dataReturn);
					ErrorMessage errorMessage = util1.checkEntity(data, data.getRowIndex());
					if (Common.isNotNull(errorMessage)){
						errorMessage.setData(dataReturn);
						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() {
					importSocialHouseUpdate(cachedDataList,errorMessageList);
				}
			}).sheet().doRead();
		}catch (Exception e){
			log.error(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR,e);
			return R.failed(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR);
		}
		if (errorMessageList.stream().allMatch(e->e.getMessage().equals(CommonConstants.UPDATE_SUCCESS))) {
			return R.ok();
		} else {
			return R.ok(errorMessageList);
		}
	}

	/**
	 * 导出社保户配置数据
	 * @return
	 */
	@Override
	public void listExport(HttpServletResponse response, SysHouseHoldInfo sysHouseHoldInfo){
		String fileName = "户配置信息批量导出" + DateUtil.getThisTime() + CommonConstants.XLSX;
		//账户性质是公积金导出空 默认是社保
		if (Common.isNotNull(sysHouseHoldInfo.getType())
				&& CommonConstants.ONE_STRING.equals(sysHouseHoldInfo.getType())) {
			sysHouseHoldInfo.setType(CommonConstants.THREE_STRING);
		}
		if (Common.isEmpty(sysHouseHoldInfo.getType())) {
			sysHouseHoldInfo.setType(CommonConstants.ZERO_STRING);
		}
		//获取要导出的列表
		List<TSocialHouseholdExportVo> list = new ArrayList<>();
		long count = baseMapper.selectExportCount(sysHouseHoldInfo);
		try (ServletOutputStream out = response.getOutputStream();) {
			response.setContentType(CommonConstants.MULTIPART_FORM_DATA);
			response.setCharacterEncoding("utf-8");
			response.setHeader(CommonConstants.CONTENT_DISPOSITION, CommonConstants.ATTACHMENT_FILENAME + URLEncoder.encode(fileName  , "UTF-8"));
			// 这里 需要指定写用哪个class去写，然后写到第一个sheet，然后文件流会自动关闭
			ExcelWriter excelWriter = EasyExcel.write(out, TSocialHouseholdExportVo.class).build();
			if (count >  CommonConstants.ZERO_INT){
				WriteSheet writeSheet;
				list = baseMapper.selectExportList(sysHouseHoldInfo);
				if (Common.isNotNull(list)) {
					writeSheet = EasyExcel.writerSheet("户配置信息批量导出").build();
					excelWriter.write(list, writeSheet);
				}
			}else {
				WriteSheet writeSheet = EasyExcel.writerSheet("户配置信息批量导出").build();
				excelWriter.write(list,writeSheet);
			}
			excelWriter.finish();
		}catch (Exception e){
			log.error("执行异常" ,e);
		}
	}

	private void importSocialHouseInsert(List<TSocialHouseholdInsertVo> excelVOList, List<ErrorMessage> errorMessageList) {
		if (!Common.isNotNull(excelVOList)){
			return;
		}
		Map<String, String> dicMap = new HashMap<>();
		Map<String,String> dicObj = (Map<String, String>) RedisUtil.redis.opsForValue()
				.get(CacheConstants.DICT_DETAILS
						+ CommonConstants.COLON_STRING
						+ "dept_config_type");
		if (Common.isNotNull(dicObj)) {
			for (Map.Entry<String, String> entry : dicObj.entrySet()) {
				String key = entry.getKey();
				String Label = entry.getValue();
				dicMap.put(Label, key);
			}
		}
		//获取所有区域数据
		HashMap<String, SysArea> areaMap = initAreaMap();
		if (Common.isEmpty(areaMap)) {
			errorMessageList.add(new ErrorMessage(1, "获取区域数据失败"));
		}
		//获取所有的人员信息
		HashMap<String, SysUser> userMap = new HashMap<>();
		R<AllUserNaVo> userListR = upmsDaprUtils.getAllUserIds();
		if (Common.isNotNull(userListR)) {
			AllUserNaVo userList = userListR.getData();
			if (null != userList && !userList.getAllUser().isEmpty()) {
				userMap = userList.getAllUser();
			}
		} else {
			errorMessageList.add(new ErrorMessage(1, "获取人员信息数据失败"));
		}

		Map<String,String> exitNameMap = new HashMap<>();
		SysHouseHoldInfo info;
		SysUser auditUser;
		SysUser handlerUser;
		String errorMsg;
		// 个性化校验逻辑
		// 执行数据插入操作组装
		TSocialHouseholdInsertVo excel;
		SysHouseHoldInfo household;
		// 判断户的审核人与办理人是否有对应的菜单和数据权限，有才可以，没有则不行
		String judgeAuth;
		for (int i = 0; i < excelVOList.size(); i++) {
			excel = excelVOList.get(i);
			//所属机构去空
			excel.setOrganName(excel.getOrganName().replace(" ",""));
			household = new SysHouseHoldInfo();
			BeanCopyUtils.copyProperties(excel,household);
			excel.setProvince(areaMap.get(excel.getProvince()).getAreaName());
			excel.setCity(areaMap.get(excel.getCity()).getAreaName());
			if (Common.isNotNull(excel.getTown())) {
				excel.setTown(areaMap.get(excel.getTown()).getAreaName());
			}
			//判断所属机构是否填写正确
			if (Common.isNotNull(dicMap) && Common.isEmpty(dicMap.get(excel.getOrganName()))) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_SEVEN,excel));
				continue;
			}

			//判断模板中是否有户重复的数据
			if (null == exitNameMap.get(excel.getName())) {
				exitNameMap.put(excel.getName(),"1");
			} else {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_SAME_HOUSE,excel));
				continue;
			}
			//判断户类型是否准确
			if (!HouseConfigConstants.HOUSE_TYPE_ONE.equals(excel.getHouseType())
					&& !HouseConfigConstants.HOUSE_TYPE_TWO.equals(excel.getHouseType())) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_ONE,excel));
				continue;
			}
			//判断是否自动生成解除劳动合同书是否准确
			if (!CommonConstants.IS_TRUE.equals(excel.getIsAutoLeaveDoc()) && !CommonConstants.IS_FALSE.equals(excel.getIsAutoLeaveDoc())) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_TWELVE,excel));
				continue;
			}
			//判断是否自动办理是否准确
			if (!CommonConstants.IS_TRUE.equals(excel.getAutoStatus()) && !CommonConstants.IS_FALSE.equals(excel.getAutoStatus())) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_THREE,excel));
				continue;
			}
			if (!CommonConstants.IS_TRUE.equals(excel.getAutoStatusYsd()) && !CommonConstants.IS_FALSE.equals(excel.getAutoStatusYsd())) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_THREE_TWO,excel));
				continue;
			}
			//社保自动化为是时必填校验
			if (CommonConstants.IS_TRUE.equals(excel.getAutoStatus())){
				if (Common.isEmpty(excel.getIsSingle())) {
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_FOURTEEN,excel));
					continue;
				}
				//判断推送类型是否准确
				if (!HouseConfigConstants.IS_SINGLE_NO.equals(excel.getIsSingle()) && !HouseConfigConstants.IS_SINGLE_YES.equals(excel.getIsSingle())) {
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_NINE,excel));
					continue;
				}
				if (Common.isEmpty(excel.getRosterAutoFlagYgs())) {
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_FIFTEEN,excel));
					continue;
				}
				//判断是否自动生成花名册 是否准确
				if (!CommonConstants.IS_TRUE.equals(excel.getRosterAutoFlagYgs()) && !CommonConstants.IS_FALSE.equals(excel.getRosterAutoFlagYgs())) {
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_TEN,excel));
					continue;
				}

			}
			//社保是否自动生成花名册为是时 社保仅生成花名册为是时必填校验
			if (CommonConstants.IS_TRUE.equals(excel.getRosterAutoFlagYgs())){
				if (Common.isEmpty(excel.getDataFlagYgs())) {
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_SIXTEEN,excel));
					continue;
				}
				//判断是否仅补缴生成材料
				if (!CommonConstants.IS_TRUE.equals(excel.getDataFlagYgs()) && !CommonConstants.IS_FALSE.equals(excel.getDataFlagYgs())) {
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_ELVEN,excel));
					continue;
				}
			}
			//医保自动化为是时必填校验
			if (CommonConstants.IS_TRUE.equals(excel.getAutoStatusYsd())){
				if (Common.isEmpty(excel.getIsSingleYsd())) {
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_SEVENTEEN,excel));
					continue;
				}
				if (Common.isEmpty(excel.getRosterAutoFlagYsd())) {
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_EIGHTEEN,excel));
					continue;
				}
				//判断推送类型是否准确
				if (!HouseConfigConstants.IS_SINGLE_NO.equals(excel.getIsSingleYsd()) && !HouseConfigConstants.IS_SINGLE_YES.equals(excel.getIsSingleYsd())) {
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_NINE_TWO,excel));
					continue;
				}
				//判断是否自动生成花名册 是否准确
				if (!CommonConstants.IS_TRUE.equals(excel.getRosterAutoFlagYsd()) && !CommonConstants.IS_FALSE.equals(excel.getRosterAutoFlagYsd())) {
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_THIRTEEN,excel));
					continue;
				}

			}
			//医保自动化为是时医保仅补缴生成材料必填校验
			if (CommonConstants.IS_TRUE.equals(excel.getRosterAutoFlagYsd())){
				if (Common.isEmpty(excel.getDataFlagYsd())) {
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_NINETEEN,excel));
					continue;
				}
				//判断是否仅补缴生成材料
				if (!CommonConstants.IS_TRUE.equals(excel.getDataFlagYsd()) && !CommonConstants.IS_FALSE.equals(excel.getDataFlagYsd())) {
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_ELVEN_TWO,excel));
					continue;
				}
			}

			//是否自动办理，选择是时，社保和医保信息必须填写其中一个，否则导入不成功--》MVP1.7.15 选择是 社保信息必填
			//选择否时，不做限制要求，可填可不填，导入时正常导入填写的字段
			if (CommonConstants.IS_TRUE.equals(excel.getAutoStatus())
					&&(Common.isEmpty(excel.getSocialAccount())
					|| Common.isEmpty(excel.getSocialPassword())) ){
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_TWO,excel));
				continue;
			}
			//MVP1.7.15 医保是否自动办理，选择是时，医保信息必须填写，否则导入不成功
			if (CommonConstants.IS_TRUE.equals(excel.getAutoStatusYsd())
					&& (Common.isEmpty(excel.getMediclAccount()) || Common.isEmpty(excel.getMediclPassword())) ){
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_TWO_TWO,excel));
				continue;
			}
			//判断社保、医保账户和密码的对应关系
			if (((Common.isEmpty(excel.getSocialAccount())) != (Common.isEmpty(excel.getSocialPassword()))) ||
					((Common.isEmpty(excel.getMediclAccount())) != (Common.isEmpty(excel.getMediclPassword())))) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_FIVE,excel));
				continue;
			}
			info = this.getOne(Wrappers.<SysHouseHoldInfo>query().lambda()
					.eq(SysHouseHoldInfo::getType,CommonConstants.ZERO_STRING)
					.eq(SysHouseHoldInfo::getName,excel.getName())
					.last(CommonConstants.LAST_ONE_SQL));
			if (null != info){
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_IS_EXIT,excel));
				continue;
			}
			auditUser = userMap.get(excel.getAuditUserName());
			handlerUser = userMap.get(excel.getHandleUserName());
			if (Common.isEmpty(auditUser)) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_AUDIT_USER,excel));
				continue;
			}
			if (Common.isEmpty(handlerUser)) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_HANDLE_USER,excel));
				continue;
			}
			// 判断审核人与办理人的权限：
			judgeAuth = this.judgeAuditAndHandleAuth(CommonConstants.ZERO_STRING
					, auditUser.getUserId(), excel.getAuditUserName()
					, handlerUser.getUserId(), excel.getHandleUserName());
			if (Common.isNotNull(judgeAuth)) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), judgeAuth ,excel));
				continue;
			}
			if(mobileCheck(excel.getPhone())) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_EIGHT,excel));
				continue;
			}
			//校验手机号准确性
			errorMsg = checkMobile(excel.getPhone());
			if (!errorMsg.contains(HouseConfigConstants.SUCESS)) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), errorMsg,excel));
				continue;
			}
			//封装和插入数据
			household.setCustomerNo(excel.getCustomerNo());
			household.setCustomerNoYsd(excel.getCustomerNoYsd());
			household.setAreaCode(areaMap.get(household.getCity()).getAreaCode());
			household.setIsAutoLeaveDoc(excel.getIsAutoLeaveDoc().equals(CommonConstants.IS_TRUE) ? "1" : "0");
			household.setAutoStatus(excel.getAutoStatus().equals(CommonConstants.IS_TRUE) ? "0" : "1");
			household.setAutoStatusYsd(excel.getAutoStatusYsd().equals(CommonConstants.IS_TRUE) ? "0" : "1");
			household.setType("0");
			household.setHouseType(excel.getHouseType().equals(HouseConfigConstants.HOUSE_TYPE_ONE) ? "1" : "0");
			household.setAuditUser(null == auditUser.getUserId() ? "" : auditUser.getUserId());
			household.setHandleUser(null == handlerUser.getUserId() ? "" :handlerUser.getUserId());
			if (Common.isNotNull(excel.getRosterAutoFlagYgs())){
				household.setRosterAutoFlagYgs(excel.getRosterAutoFlagYgs().equals(CommonConstants.IS_TRUE) ? "1" : "0");
			}
			if (Common.isNotNull(excel.getDataFlagYgs())){
				household.setDataFlagYgs(excel.getDataFlagYgs().equals(CommonConstants.IS_TRUE) ? "1" : "0");
			}
			if (Common.isNotNull(excel.getIsSingle())){
				household.setIsSingle(excel.getIsSingle().equals(HouseConfigConstants.IS_SINGLE_NO) ? "0" : "1");
			}
			if (Common.isNotNull(excel.getRosterAutoFlagYsd())){
				household.setRosterAutoFlagYsd(excel.getRosterAutoFlagYsd().equals(CommonConstants.IS_TRUE) ? "1" : "0");
			}
			if (Common.isNotNull(excel.getDataFlagYsd())){
				household.setDataFlagYsd(excel.getDataFlagYsd().equals(CommonConstants.IS_TRUE) ? "1" : "0");
			}
			if (Common.isNotNull(excel.getIsSingleYsd())){
				household.setIsSingleYsd(excel.getIsSingleYsd().equals(HouseConfigConstants.IS_SINGLE_NO) ? "0" : "1");
			}

			household.setOrganId(dicMap.get(household.getOrganName()));
			baseMapper.insert(household);
			// 同步审核权限、办理权限
			this.saveAuditUserOrHandleUser(household, CommonConstants.ZERO_STRING);
			this.saveAuditUserOrHandleUser(household, CommonConstants.ONE_STRING);
			errorMessageList.add(new ErrorMessage(excel.getRowIndex(),CommonConstants.SAVE_SUCCESS,excel));
		}
	}


	private void importSocialHouseUpdate(List<TSocialHouseholdUpdateVo> excelVOList, List<ErrorMessage> errorMessageList) {
		if (!Common.isNotNull(excelVOList)){
			return;
		}
		Map<String, String> dicMap = new HashMap<>();
		Map<String,String> dicObj = (Map<String, String>) RedisUtil.redis.opsForValue()
				.get(CacheConstants.DICT_DETAILS
						+ CommonConstants.COLON_STRING
						+ "dept_config_type");
		if (Common.isNotNull(dicObj)) {
			for (Map.Entry<String, String> entry : dicObj.entrySet()) {
				String key = entry.getKey();
				String Label = entry.getValue();
				dicMap.put(Label, key);
			}
		}
		//获取所有区域数据
		HashMap<String, SysArea> areaMap = initAreaMap();
		if (Common.isEmpty(areaMap)) {
			errorMessageList.add(new ErrorMessage(1, "获取区域数据失败"));
		}
		//获取所有的人员信息
		HashMap<String, SysUser> userMap = new HashMap<>();
		R<AllUserNaVo> userListR = upmsDaprUtils.getAllUserIds();
		if (Common.isNotNull(userListR)) {
			AllUserNaVo userList = userListR.getData();
			if (null != userList && !userList.getAllUser().isEmpty()) {
				userMap = userList.getAllUser();
			}
		} else {
			errorMessageList.add(new ErrorMessage(1, "获取人员信息数据失败"));
		}
		Map<String,String> exitNameMap = new HashMap<>();
		SysHouseHoldInfo info;
		String errorMsg;
		// 个性化校验逻辑
		// 执行数据插入操作 组装
		SysUser auditUser;
		SysUser handlerUser;
		// 判断户的审核人与办理人是否有对应的菜单和数据权限，有才可以，没有则不行
		String judgeAuth;
		for (int i = 0; i < excelVOList.size(); i++) {
			TSocialHouseholdUpdateVo excel = excelVOList.get(i);
			//校验省市县
			if (Common.isNotNull(excel.getProvince()) && Common.isEmpty(excel.getCity())) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_SIX,excel));
				continue;
			}
			info = this.getOne(Wrappers.<SysHouseHoldInfo>query().lambda()
					.eq(SysHouseHoldInfo::getType,CommonConstants.ZERO_STRING)
					.eq(SysHouseHoldInfo::getName,excel.getName())
					.last(CommonConstants.LAST_ONE_SQL));
			if (Common.isEmpty(info)){
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_NOT_EXIT,excel));
				continue;
			}
			if (Common.isNotNull(excel.getProvince()) && Common.isNotNull(excel.getCity())) {
				info.setProvince(excel.getProvince());
				info.setCity(excel.getCity());
				info.setAreaCode(areaMap.get(excel.getCity()).getAreaCode());
				if (Common.isNotNull(excel.getTown())) {
					info.setTown(excel.getTown());
				} else {
					info.setTown("");
				}
			}
			if (Common.isNotNull(excel.getProvince())) {
				excel.setProvince(areaMap.get(excel.getProvince()).getAreaName());
			}
			if (Common.isNotNull(excel.getCity())) {
				excel.setCity(areaMap.get(excel.getCity()).getAreaName());
			}
			if (Common.isNotNull(excel.getTown())) {
				excel.setTown(areaMap.get(excel.getTown()).getAreaName());
			}

			if (Common.isNotNull(excel.getOrganName())) {
				excel.setOrganName(excel.getOrganName().replace(" ",""));
				if (Common.isNotNull(dicMap) && Common.isEmpty(dicMap.get(excel.getOrganName()))) {
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_SEVEN, excel));
					continue;
				} else {
					info.setOrganId(dicMap.get(excel.getOrganName()));
				}
			}

			//判断模板中是否有户重复的数据
			if (null == exitNameMap.get(excel.getName())) {
				exitNameMap.put(excel.getName(),"1");
			} else {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_SAME_HOUSE,excel));
				continue;
			}
			//判断户类型是否准确
			if (Common.isNotNull(excel.getHouseType()) && !HouseConfigConstants.HOUSE_TYPE_ONE.equals(excel.getHouseType())
					&& !HouseConfigConstants.HOUSE_TYPE_TWO.equals(excel.getHouseType())) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_ONE,excel));
				continue;
			}
			//判断社保自动化是否为空
			if (Common.isEmpty(excel.getAutoStatus())) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_TWENTY,excel));
				continue;
			}
			//判断医保自动化是否为空
			if (Common.isEmpty(excel.getAutoStatusYsd())) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_TWENTY_ONE,excel));
				continue;
			}
			//判断是否自动办理是否准确
			if (Common.isNotNull(excel.getAutoStatus())
					&& !CommonConstants.IS_TRUE.equals(excel.getAutoStatus())
					&& !CommonConstants.IS_FALSE.equals(excel.getAutoStatus())) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_THREE,excel));
				continue;
			}
			if (Common.isNotNull(excel.getAutoStatusYsd())
					&& !CommonConstants.IS_TRUE.equals(excel.getAutoStatusYsd())
					&& !CommonConstants.IS_FALSE.equals(excel.getAutoStatusYsd())) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_THREE_TWO,excel));
				continue;
			}

			//判断推送类型是否准确
			if (Common.isNotNull(excel.getIsSingle())
					&& !HouseConfigConstants.IS_SINGLE_NO.equals(excel.getIsSingle())
					&& !HouseConfigConstants.IS_SINGLE_YES.equals(excel.getIsSingle())) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_NINE,excel));
				continue;
			}
			if (Common.isNotNull(excel.getIsSingleYsd())
					&& !HouseConfigConstants.IS_SINGLE_NO.equals(excel.getIsSingleYsd())
					&& !HouseConfigConstants.IS_SINGLE_YES.equals(excel.getIsSingleYsd())) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_NINE_TWO,excel));
				continue;
			}
			//判断是否自动生成花名册 是否准确
			if (Common.isNotNull(excel.getRosterAutoFlagYgs())
					&& !CommonConstants.IS_TRUE.equals(excel.getRosterAutoFlagYgs())
					&& !CommonConstants.IS_FALSE.equals(excel.getRosterAutoFlagYgs())) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_TEN,excel));
				continue;
			}
			if (Common.isNotNull(excel.getRosterAutoFlagYsd())
					&& !CommonConstants.IS_TRUE.equals(excel.getRosterAutoFlagYsd())
					&& !CommonConstants.IS_FALSE.equals(excel.getRosterAutoFlagYsd())) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_THIRTEEN,excel));
				continue;
			}
			//社保是否自动生成花名册为是时 社保仅补缴生成材料必填
			if (CommonConstants.IS_TRUE.equals(excel.getRosterAutoFlagYgs())){
				if (Common.isEmpty(excel.getDataFlagYgs())) {
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_SIXTEEN,excel));
					continue;
				}
				//判断是否仅补缴生成材料是否准确
				if (Common.isNotNull(excel.getDataFlagYgs())
						&& !CommonConstants.IS_TRUE.equals(excel.getDataFlagYgs())
						&& !CommonConstants.IS_FALSE.equals(excel.getDataFlagYgs())) {
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_ELVEN,excel));
					continue;
				}
			}
			//医保是否自动生成花名册为是时 医保仅补缴生成材料必填
			if (CommonConstants.IS_TRUE.equals(excel.getRosterAutoFlagYsd())){
				if (Common.isEmpty(excel.getDataFlagYsd())){
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_NINETEEN,excel));
					continue;
				}
				//判断是否仅补缴生成材料是否准确
				if (Common.isNotNull(excel.getDataFlagYsd())
						&& !CommonConstants.IS_TRUE.equals(excel.getDataFlagYsd())
						&& !CommonConstants.IS_FALSE.equals(excel.getDataFlagYsd())) {
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_ELVEN_TWO,excel));
					continue;
				}
			}


			//是否自动办理，选择是时，社保和医保信息必须填写其中一个，否则导入不成功 --》MVP1.7.15 社保自动化，选择否时，医保信息必须填写，否则导入不成功
			//选择否时，不做限制要求，可填可不填，导入时正常导入填写的字段
			// MVP1.7.15 医保自动化，选择是时，医保信息必须填写，否则导入不成功
			if (Common.isNotNull(excel.getAutoStatus()) &&
					CommonConstants.IS_TRUE.equals(excel.getAutoStatus())
					&& (Common.isEmpty(excel.getSocialAccount())
					|| Common.isEmpty(excel.getIsSingle())
					|| Common.isEmpty(excel.getRosterAutoFlagYgs()))){
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_TWO,excel));
				continue;
			}
			if (Common.isNotNull(excel.getAutoStatusYsd()) &&
					CommonConstants.IS_TRUE.equals(excel.getAutoStatusYsd())
					&& (Common.isEmpty(excel.getMediclAccount())
					|| Common.isEmpty(excel.getIsSingleYsd())
					|| Common.isEmpty(excel.getRosterAutoFlagYsd()))) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_TWO_TWO,excel));
				continue;
			}

			//判断社保、医保账户和密码的对应关系
			if (((Common.isEmpty(excel.getSocialAccount())) != (Common.isEmpty(excel.getSocialPassword()))) ||
					((Common.isEmpty(excel.getMediclAccount())) != (Common.isEmpty(excel.getMediclPassword())))) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_FIVE,excel));
				continue;
			}
			if (Common.isNotNull(excel.getAuditUserName())) {
				auditUser = userMap.get(excel.getAuditUserName());
				if (auditUser == null || Common.isEmpty(auditUser.getUserId())) {
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_AUDIT_USER, excel));
					continue;
				} else {
					// 判断审核人与办理人的权限：
					judgeAuth = this.judgeAuditAndHandleAuth(CommonConstants.ZERO_STRING
							, auditUser.getUserId(), excel.getAuditUserName()
							, null, null );
					if (Common.isNotNull(judgeAuth)) {
						errorMessageList.add(new ErrorMessage(excel.getRowIndex(), judgeAuth ,excel));
						continue;
					}
				}
			}
			if (Common.isNotNull(excel.getHandleUserName())) {
				handlerUser = userMap.get(excel.getHandleUserName());
				if (handlerUser == null || Common.isEmpty(handlerUser.getUserId())) {
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_HANDLE_USER, excel));
					continue;
				} else {
					// 判断审核人与办理人的权限：
					judgeAuth = this.judgeAuditAndHandleAuth(CommonConstants.ZERO_STRING
							, null, null
							, handlerUser.getUserId(), excel.getHandleUserName() );
					if (Common.isNotNull(judgeAuth)) {
						errorMessageList.add(new ErrorMessage(excel.getRowIndex(), judgeAuth ,excel));
						continue;
					}
				}
			}

			if(Common.isNotNull(excel.getPhone()) && mobileCheck(excel.getPhone())) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_EIGHT,excel));
				continue;
			}

			//校验手机号准确性
			if (Common.isNotNull(excel.getPhone())) {
				errorMsg = checkMobile(excel.getPhone());
				if (!errorMsg.contains(HouseConfigConstants.SUCESS)) {
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), errorMsg, excel));
					continue;
				}
			}
			// 新老数据审核人办理人不同，先删除，再添加
			if (Common.isNotNull(excel.getAuditUserName()) && !excel.getAuditUserName().equals(info.getAuditUserName())) {
				tSocialfundHouseResService.deleteAuditUser(info);
				// 同步审核权限
				this.saveAuditUserOrHandleUser(info, CommonConstants.ONE_STRING);
			}
			if (Common.isNotNull(excel.getHandleUserName()) && !excel.getHandleUserName().equals(info.getHandleUserName())) {
				tSocialfundHouseResService.deleteHandleUser(info);
				// 同步办理权限
				this.saveAuditUserOrHandleUser(info, CommonConstants.ZERO_STRING);
			}
			//更新数据

			updateHouseInfo(excel,info,userMap);
			errorMessageList.add(new ErrorMessage(excel.getRowIndex(),CommonConstants.UPDATE_SUCCESS,excel));
		}
	}

	/**
	 * 校验手机号准确性
	 * @param mobileNo 社保户公积金户数据
	 * @return
	 */
	private String checkMobile(String mobileNo) {
		// 调用校验服务-校验手机号
		TCheckMobile checkMobile = new TCheckMobile();
		checkMobile.setMobile(mobileNo);
		R<TCheckMobile> a = HttpDaprUtil.invokeMethodPost(daprCheckProperties.getAppUrl(), daprCheckProperties.getAppId()
				, "/tcheckmobile/inner/checkOneMobile", checkMobile, TCheckMobile.class, SecurityConstants.FROM_IN);
		if (a != null && a.getData() != null) {
			checkMobile = a.getData();
			if (checkMobile != null && Common.isNotNull(checkMobile.getStatus())) {
				if (!CommonConstants.ONE_STRING.equals(checkMobile.getStatus())) {
					return checkMobile.getMessage();
				} else {
					return "成功";
				}
			}
		}
		return "校验服务错误，请联系管理员！";
	}

	private void updateHouseInfo (TSocialHouseholdUpdateVo excel,SysHouseHoldInfo info,
								  Map<String,SysUser> userMap) {
		if (Common.isNotNull(excel.getHouseType())) {
			info.setHouseType(excel.getHouseType().equals(HouseConfigConstants.HOUSE_TYPE_ONE) ? "1" : "0");
		}
		if (Common.isNotNull(excel.getIsAutoLeaveDoc())) {
			info.setIsAutoLeaveDoc(excel.getIsAutoLeaveDoc().equals(CommonConstants.IS_TRUE) ? "1" : "0");
		}
		if (Common.isNotNull(excel.getAutoStatus())) {
			info.setAutoStatus(excel.getAutoStatus().equals(CommonConstants.IS_TRUE) ? "0" : "1");
		}
		if (Common.isNotNull(excel.getAutoStatusYsd())) {
			info.setAutoStatusYsd(excel.getAutoStatusYsd().equals(CommonConstants.IS_TRUE) ? "0" : "1");
		}
		if (Common.isNotNull(excel.getIsSingle())) {
			info.setIsSingle(excel.getIsSingle().equals(HouseConfigConstants.IS_SINGLE_NO) ? "0" : "1");
		}
		if (Common.isNotNull(excel.getIsSingleYsd())) {
			info.setIsSingleYsd(excel.getIsSingleYsd().equals(HouseConfigConstants.IS_SINGLE_NO) ? "0" : "1");
		}
		if (Common.isNotNull(excel.getRosterAutoFlagYgs())) {
			info.setRosterAutoFlagYgs(excel.getRosterAutoFlagYgs().equals(CommonConstants.IS_TRUE) ? "1" : "0");
		}
		if (Common.isNotNull(excel.getRosterAutoFlagYsd())) {
			info.setRosterAutoFlagYsd(excel.getRosterAutoFlagYsd().equals(CommonConstants.IS_TRUE) ? "1" : "0");
		}
		if (Common.isNotNull(excel.getDataFlagYgs())) {
			info.setDataFlagYgs(excel.getDataFlagYgs().equals(CommonConstants.IS_TRUE) ? "1" : "0");
		}
		if (Common.isNotNull(excel.getDataFlagYsd())) {
			info.setDataFlagYsd(excel.getDataFlagYsd().equals(CommonConstants.IS_TRUE) ? "1" : "0");
		}
		if (Common.isNotNull(excel.getOrganName())) {
			info.setOrganName(excel.getOrganName());
		}
		if (Common.isNotNull(excel.getPhone())) {
			info.setPhone(excel.getPhone());
		}
		if (Common.isNotNull(excel.getCustomerNo())) {
			info.setCustomerNo(excel.getCustomerNo());
		}
		if (Common.isNotNull(excel.getCustomerNoYsd())) {
			info.setCustomerNoYsd(excel.getCustomerNoYsd());
		}
		if (Common.isNotNull(excel.getUnitCreditCode())) {
			info.setUnitCreditCode(excel.getUnitCreditCode());
		}
		if (Common.isNotNull(excel.getCustomerNoYsd())) {
			info.setCustomerNoYsd(excel.getCustomerNoYsd());
		}
		if (Common.isNotNull(excel.getSocialAccount())) {
			info.setSocialAccount(excel.getSocialAccount());
		}
		if (Common.isNotNull(excel.getSocialPassword())) {
			info.setSocialPassword(excel.getSocialPassword());
		}
		if (Common.isNotNull(excel.getMediclAccount())) {
			info.setMediclAccount(excel.getMediclAccount());
		}
		if (Common.isNotNull(excel.getMediclPassword())) {
			info.setMediclPassword(excel.getMediclPassword());
		}
		if (Common.isNotNull(excel.getAuditUserName())) {
			SysUser auditUser = userMap.get(excel.getAuditUserName());
			info.setAuditUser(auditUser.getUserId());
			info.setAuditUserName(excel.getAuditUserName());
		}
		if (Common.isNotNull(excel.getHandleUserName())) {
			SysUser handlerUser = userMap.get(excel.getHandleUserName());
			info.setHandleUser(handlerUser.getUserId());
			info.setHandleUserName(excel.getHandleUserName());
		}
		baseMapper.updateById(info);
	}

	//获取所有区域数据
	private HashMap<String,SysArea> initAreaMap() {
		HashMap<String,SysArea> areaMap = new HashMap<>();
		R<AreaVo> areaListR = upmsDaprUtils.getAreaListR();
		if (null == areaListR || areaListR.getCode() != CommonConstants.SUCCESS) {
			return new HashMap<>();
		}
		AreaVo areaList = areaListR.getData();
		if (null != areaList && !areaList.getSysAreaList().isEmpty()) {
			for (SysArea area : areaList.getSysAreaList()) {
				areaMap.put(Integer.toString(area.getId()), area);
			}
		} else {
			return new HashMap<>();
		}
		return areaMap;
	}

	private boolean mobileCheck(String number) {
		String regex = "^1[3-9]\\d{9}$";
		// 编译正则表达式
		Pattern pattern = Pattern.compile(regex);
		// 匹配正则表达式
		Matcher matcher = pattern.matcher(number);
		// 返回是否匹配结果
		return !matcher.matches();
	}
}
