/*
 *    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.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.SysBaseSetInfo;
import com.yifu.cloud.plus.v1.yifu.social.entity.SysHouseHoldInfo;
import com.yifu.cloud.plus.v1.yifu.social.entity.TAttaInfo;
import com.yifu.cloud.plus.v1.yifu.social.entity.TSocialfundHouseRes;
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.SysHouseHoldInfoService;
import com.yifu.cloud.plus.v1.yifu.social.service.TAttaInfoService;
import com.yifu.cloud.plus.v1.yifu.social.service.TSocialfundHouseResService;
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.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;

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

	private final SysBaseSetInfoMapper baseSetInfoMapper;

	@Autowired
	private TSocialfundHouseResService tSocialfundHouseResService;

	private final TAttaInfoService attaInfoService;

	private final DaprCheckProperties daprCheckProperties;

	@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("审核人或办理人必填！");
		}
		//获取行政区化代码
		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());
				}
			}
		}
		baseMapper.insert(sysHouseHoldInfo);
		//维护附件信息
		if (Common.isNotNull(sysHouseHoldInfo.getAttaId())) {
			TAttaInfo attaInfo = attaInfoService.getById(sysHouseHoldInfo.getAttaId());
			attaInfo.setDomainId(sysHouseHoldInfo.getId());
			attaInfoService.updateById(attaInfo);
		}
		// 同步审核权限、办理权限
		this.saveAuditUserOrHandleUser(sysHouseHoldInfo, CommonConstants.ZERO_STRING);
		this.saveAuditUserOrHandleUser(sysHouseHoldInfo, CommonConstants.ONE_STRING);
		return R.ok();
	}

	/**
	 * 查询
	 * @param id
	 * @return
	 */
	@Override
	public R<SysHouseHoldInfo> getByIdAtta(String id) {
		SysHouseHoldInfo sysHouseHoldInfo = baseMapper.selectById(id);
		TAttaInfo attaInfo = attaInfoService.getOne(Wrappers.<TAttaInfo>query().lambda().eq(TAttaInfo::getDomainId, id)
				.last(CommonConstants.LAST_ONE_SQL));
		if (Common.isNotNull(attaInfo)) {
			URL url = ossUtil.getObjectUrl(null, attaInfo.getAttaSrc());
			if (Common.isNotNull(url)) {
				attaInfo.setAttaUrl(url.toString());
			}
			sysHouseHoldInfo.setAtta(attaInfo);
		}
		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) {
		//户名称去空格
		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 (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());
				}
			}
		}
		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);
		}
	}

	@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;
		//获取要导出的列表
		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;
		// 个性化校验逻辑
		// 执行数据插入操作组装
		for (int i = 0; i < excelVOList.size(); i++) {
			TSocialHouseholdInsertVo excel = excelVOList.get(i);
			//所属机构去空
			excel.setOrganName(excel.getOrganName().replace(" ",""));
			SysHouseHoldInfo 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 (!excel.getHouseType().equals(HouseConfigConstants.HOUSE_TYPE_ONE)
					&& !excel.getHouseType().equals(HouseConfigConstants.HOUSE_TYPE_TWO)) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_ONE,excel));
				continue;
			}
			//判断是否自动办理是否准确
			if (!excel.getAutoStatus().equals(CommonConstants.IS_TRUE) && !excel.getAutoStatus().equals(CommonConstants.IS_FALSE)) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_THREE,excel));
				continue;
			}
			//是否自动办理，选择是时，社保和医保信息必须填写其中一个，否则导入不成功
			//选择否时，不做限制要求，可填可不填，导入时正常导入填写的字段
			if (excel.getAutoStatus().equals(CommonConstants.IS_TRUE) && Common.isEmpty(excel.getSocialAccount())
					&& Common.isEmpty(excel.getMediclAccount())){
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_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) || Common.isEmpty(handlerUser)) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_FOUR,excel));
				continue;
			}
			//校验手机号准确性
			errorMsg = checkMobile(excel.getPhone());
			if (!errorMsg.contains(HouseConfigConstants.SUCESS)) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), errorMsg,excel));
				continue;
			}
			//封装和插入数据
			household.setAreaCode(areaMap.get(household.getCity()).getAreaCode());
			household.setAutoStatus(excel.getAutoStatus().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());
			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;
		// 个性化校验逻辑
		// 执行数据插入操作 组装
		for (int i = 0; i < excelVOList.size(); i++) {
			TSocialHouseholdUpdateVo excel = excelVOList.get(i);
			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.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.isEmpty(info)){
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_NOT_EXIT,excel));
				continue;
			}
			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 (Common.isNotNull(excel.getProvince()) && Common.isEmpty(excel.getProvince())) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_SIX,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 (info.getAutoStatus().equals(CommonConstants.IS_TRUE) && excel.getAutoStatus().equals(CommonConstants.IS_TRUE) &&
					Common.isEmpty(excel.getSocialAccount()) && Common.isEmpty(excel.getMediclAccount())){
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_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.getHouseType()) && !excel.getHouseType().equals(HouseConfigConstants.HOUSE_TYPE_ONE)
					&& !excel.getHouseType().equals(HouseConfigConstants.HOUSE_TYPE_TWO)) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_ONE,excel));
				continue;
			}
			//判断是否自动办理是否准确
			if (!excel.getAutoStatus().equals(CommonConstants.IS_TRUE) && !excel.getAutoStatus().equals(CommonConstants.IS_FALSE)) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_THREE,excel));
				continue;
			}
			if ((Common.isNotNull(excel.getAuditUserName()) && Common.isEmpty(userMap.get(excel.getAuditUserName())))
					|| (Common.isNotNull(excel.getHandleUserName()) && Common.isEmpty(userMap.get(excel.getHandleUserName())))) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), HouseConfigConstants.ERROR_TEMPLATE_FOUR, 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())
					&& !CommonConstants.ONE_STRING.equals(checkMobile.getStatus())) {
				return checkMobile.getMessage();
			}
		}
		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.getAutoStatus())) {
			info.setAutoStatus(excel.getAutoStatus().equals(CommonConstants.IS_TRUE) ? "0" : "1");
		}
		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.getUnitCreditCode())) {
			info.setUnitCreditCode(excel.getUnitCreditCode());
		}
		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;
	}
}
