package com.scpyun.platform.jilinsscgsdp.service.impl;

import cn.hutool.core.util.IdcardUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.obs.services.ObsClient;
import com.obs.services.model.ObsObject;
import com.obs.services.model.PutObjectRequest;
import com.obs.services.model.PutObjectResult;
import com.scpyun.base.bean.Page;
import com.scpyun.base.core.annotation.Api;
import com.scpyun.base.core.annotation.ApiOperation;
import com.scpyun.base.core.exception.CustomException;
import com.scpyun.base.core.utils.*;
import com.scpyun.base.db.service.CommonService;
import com.scpyun.base.utils.DateUtils;
import com.scpyun.platform.jilinsscgsdp.enums.FamilyRelationshipEnum;
import com.scpyun.platform.jilinsscgsdp.enums.HousingType;
import com.scpyun.platform.jilinsscgsdp.enums.PoliticalStatusEnum;
import com.scpyun.platform.jilinsscgsdp.utils.DateUtil;
import com.scpyun.platform.jilinsscgsdp.utils.EmojiFilterUtils;
import com.scpyun.platform.jilinsscgsdp.utils.RedisTemplateUtils;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.ParseException;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;


@Api("execl用户导入")
@Service("GridUserImportService")
@Slf4j
public class GridUserImportServiceImpl {

    private String localUrl = Global.getConfig("obs.upload.local.path");
    private String showPoint = Global.getConfig("obs.showPoint");
    private String bucketName = Global.getConfig("obs.bucketName");

    private static final List<String> FIELD_NAMES = new ArrayList<>(Arrays.asList(
            "gardenName", "residentialName", "buildingName", "unitName", "floorNum",
            "doorplateNum", "userName", "sex", "folk", "cardno",
            "politicalOutlook", "livingCondition", "tel", "hjAddress", "nowAddress",
            "relation", "juzhuType", "hujiType", "userType", "flagOne",
            "flagTwo", "flagThree", "flagFour", "flagFive", "remarks", "errorReason"
    ));

    @Autowired
    CommonService commonService;

    private final String nameSpace = "com.scpyun.platform.standard.jilinsscgsdp.JiLinImportUser.";

    private final String sysNameSpace = "com.scpyun.platform.standard.jilinsscgsdp.sys.";

    private final String officeSpace = "com.scpyun.platform.standard.jilinsscgsdp.sysOfficeinfo.";

    private final String gardenNameSpace = "com.scpyun.platform.standard.jilinsscgsdp.jlGridGardenInfo.";

    private final String residentialNameSpace = "com.scpyun.platform.standard.jilinsscgsdp.gridResidential.";

    private final String buildingNameSpace = "com.scpyun.platform.standard.jilinsscgsdp.jlGridBuilding.";

    private final String communityNameSpace = "com.scpyun.platform.standard.jilinsscgsdp.gridCommunity.";

    private final String unitNameSpace = "com.scpyun.platform.standard.jilinsscgsdp.GridUnit.";

    private final String floorNameSpace = "com.scpyun.platform.standard.jilinsscgsdp.GridFloorInfo.";

    private final String doorplateNameSpace = "com.scpyun.platform.standard.jilinsscgsdp.GridDoorplate.";

    private final String userNameSpace = "com.scpyun.platform.standard.jilinsscgsdp.user.";

    private final String focusgroupNameSpace = "com.scpyun.platform.standard.jilinsscgsdp.gridfocusgroup.";

    private final String errorExeclNameSpace = "com.scpyun.platform.standard.jilinsscgsdp.importErrorExecl.";

    private static final String redis = "grid";

    /**
     * 验证手机号或座机号的正则表达式
     * 支持格式：
     * 1. 手机号：11位数字，以1开头
     * 2. 座机号：带区号的格式如010-12345678或0571-1234567
     * 3. 不带区号的座机号：7-8位数字
     */
    private final String PHONE_REGEX =
            "^(1\\d{10})$|^((0\\d{2,3})-)?(\\d{7,8})$";

    @Autowired
    private ObsClient obsClient;

    RedissonClient redissonClient = SpringContextHolder.getBean(RedissonClient.class);

    /**
     * 导出 异常execl
     *
     * @param map
     * @param response
     * @throws IOException
     */
    @ApiOperation(value = "导出异常execl（首选）", desc = "导出异常execl（首选）", nologin = true)
    public void downloadExecl(Map<String, Object> map, HttpServletResponse response) throws IOException {
        ServletOutputStream out = null;
        InputStream obsStream = null;
        ByteArrayOutputStream bos = null;
        if (StringUtils.isEmpty(map.get("obsKey"))) {
            throw new CustomException("obsKey不可为空！");
        }
        try {
            log.info("进入方法 获取uuid=" + map.get("obsKey"));
            ObsObject obsObject = obsClient.getObject(bucketName, StringUtils.toStr(map.get("obsKey")));
            log.info("进入方法 obs中获取obsObjectJson===" + JSONUtil.toJsonStr(obsObject));
            obsStream = obsObject.getObjectContent();
//            BufferedImage bufferedImage = ImageIO.read(obsStream);
            if (obsStream != null) {
                byte[] b = new byte[1024];
                bos = new ByteArrayOutputStream();
                int len;
                while ((len = obsStream.read(b)) != -1) {
                    bos.write(b, 0, len);
                }
                log.info("进入方法ByteArrayOutputStream=======" + bos.toByteArray());
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                response.setCharacterEncoding("utf-8");
                String fileName = URLEncoder.encode(String.valueOf(map.get("fileName") + "问题数据"), "UTF-8").replaceAll("\\+", "%20");
                response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
                out = response.getOutputStream();
                out.write(bos.toByteArray());
            } else {
                throw new CustomException("文件下载失败");
            }
        } catch (Exception e) {
            log.error("=========================================================================================>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>文件下载异常{}时间{}", e.toString(), new Date());
            out = response.getOutputStream();
            List<Map<String, Object>> errorArrayList = commonService.findList(errorExeclNameSpace + "getErreExecl", map.get("jobId"));
            if (CollectionUtils.isEmpty(errorArrayList)) {
                throw new CustomException("数据为空");
            }
            errorArrayList.forEach(v -> {
                String keyFocusPersonnelType = String.valueOf(v.get("keyFocusPersonnelType"));
                String[] keyFocusPersonnelTypes = keyFocusPersonnelType.split(",");
                if (!keyFocusPersonnelTypes[0].equals("0")) {
                    v.put("flagOne", keyFocusPersonnelTypes[0]);
                } else {
                    v.put("flagOne", " ");
                }
                if (!keyFocusPersonnelTypes[1].equals("0")) {
                    v.put("flagTwo", keyFocusPersonnelTypes[1]);
                } else {
                    v.put("flagTwo", " ");
                }
                if (!keyFocusPersonnelTypes[2].equals("0")) {
                    v.put("flagThree", keyFocusPersonnelTypes[2]);
                } else {
                    v.put("flagThree", " ");
                }
                if (!keyFocusPersonnelTypes[3].equals("0")) {
                    v.put("flagFour", keyFocusPersonnelTypes[3]);
                } else {
                    v.put("flagFour", " ");
                }
                if (!keyFocusPersonnelTypes[4].equals("0")) {
                    v.put("flagFive", keyFocusPersonnelTypes[4]);
                } else {
                    v.put("flagFive", " ");
                }
            });
            // web环境下导出设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode(String.valueOf(map.get("fileName") + "问题数据"), "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            // 使用 EasyExcel 写入流
            EasyExcel.write(out)
                    .head(getHead()) // 设置表头
                    .sheet("问题数据") // 工作表名称
                    .doWrite(convertData(errorArrayList)); // 写入数据
        } finally {
            obsStream.close();
            bos.flush();
            bos.close();
            out.flush();
            out.close();
        }

    }


    /**
     * 上传文件到obs 流上传
     *
     * @param file 文件
     * @return obs上传记录
     */
    @ApiOperation(value = "execl（首选）", desc = "execl（首选）", nologin = true)
    public Map<String, Object> uploadExecl(Map<String, Object> map, MultipartFile file) {
        if (BigDecimal.valueOf((double) file.getSize() / 1024 / 1024).compareTo(BigDecimal.valueOf(50)) > 0) {
            throw new RuntimeException("上传文件过大");
        }
        String date = DateUtils.convertDate2String(DateUtil.YEAR_MONTH_DAY_PATTERN, new Date());
        long currentTimeMillis = System.currentTimeMillis();
        log.info("文件上传大小:{}key:{}",BigDecimal.valueOf((double) file.getSize() / 1024 / 1024),"userImport"+date+":"+currentTimeMillis);
        JedisUtils.set("userImport"+date+":"+currentTimeMillis,String.valueOf((double) file.getSize() / 1024 / 1024),60*60*24);
        String userId = String.valueOf(map.get("userId"));
        String fileUuid = UUID.randomUUID().toString();
        PutObjectRequest request = new PutObjectRequest(bucketName, fileUuid);
        InputStream inputStream = null;
        PutObjectResult putObjectResult = null;
        Map<String, Object> returnMap = new HashMap<>();
        try {
            inputStream = file.getInputStream();
            request.setInput(inputStream);
            putObjectResult = obsClient.putObject(request);
        } catch (Exception e) {
            UnifyLogger.parent(UnifyLogger.getTrace(e), UnifyLogger.Level.INFO);
            returnMap.put("orginalObsUploadFailReason", e.toString());
            returnMap.put("deal_result", 3);
            throw new CustomException("上传文件失败");
        } finally {
            String downloadUrl = "";
            if (putObjectResult != null) {
                String objectUrl = putObjectResult.getObjectUrl();
                if (StringUtils.isNotBlank(objectUrl)) {
                    //替换obs下载地址ip
                    Pattern pattern = Pattern.compile("/");
                    Matcher findMatcher = pattern.matcher(objectUrl);
                    int number = 0;
                    while (findMatcher.find()) {
                        number++;
                        //当“/”第二次出现时停止
                        if (number == 3) {
                            break;
                        }
                    }
                    int i = findMatcher.start();
                    downloadUrl = showPoint + objectUrl.substring(i);
                }
            }
            returnMap.put("fileName", file.getOriginalFilename());
            returnMap.put("orginalObsKey", fileUuid);
            returnMap.put("orginalObsUrl", downloadUrl);
            returnMap.put("jobStatus", 0);
            returnMap.put("createBy", userId);
            String officeId = commonService.getObject(sysNameSpace + "selectUserOfficeId", userId);
            returnMap.put("officeId", officeId);
            returnMap.put("createTime", new Date());
            commonService.insert(nameSpace + "saveImportUserJob", returnMap);
            return returnMap;
        }

    }

    /**
     * execl任务列表
     *
     * @param page
     * @return
     */
    @ApiOperation(value = "execl任务列表", desc = "execl任务列表", nologin = true)
    public Page getExeclJobList(Page page) throws ParseException {
        if (CollectionUtils.isEmpty(page.getParams())) {
            if (Objects.nonNull(page.getParams().get("importTimeStar"))&&StringUtils.isNotBlank(String.valueOf(page.getParams().get("importTimeStar")))) {
                page.getParams().put("importTimeStar", DateUtil.parseTime(String.valueOf(page.getParams().get("importTimeStar"))));
            }
            if (Objects.nonNull(page.getParams().get("importTimeEnd"))&&StringUtils.isNotBlank(String.valueOf(page.getParams().get("importTimeEnd")))) {
                page.getParams().put("importTimeEnd", DateUtil.parseTime(String.valueOf(page.getParams().get("importTimeEnd"))));
            }
        }
        LocalDate now = LocalDate.now();
        LocalDate sevenDaysBefore = now.minusDays(7); // 计算7天前
        page.getParams().put("sevenDaysBefore",sevenDaysBefore);
        Page commonServicePage = commonService.findPage(nameSpace + "selectUserImportPage", page);
        List<HashMap<String, Object>> results = commonServicePage.getResults();
        results.forEach(v -> {
            switch (String.valueOf(v.get("jobStatus"))) {
                case "0":
                    v.put("jobStatus", "未处理");
                    break;
                case "1":
                    v.put("jobStatus", "处理中");
                    break;
                case "2":
                    v.put("jobStatus", "已完成");
                    break;
                default:
                    throw new CustomException("数据异常请联系管理员！！！！");
            }

        });
        commonServicePage.setResults(results);
        return commonServicePage;
    }

    public HashMap<String, Integer> GirdUserImprotJobTask(HashMap<String, Object> map) {
        ObsObject obsObject = obsClient.getObject(bucketName, String.valueOf(map.get("orginalObsKey")));
        InputStream obsStream = obsObject.getObjectContent();
        if (obsStream == null) {
            throw new CustomException("文件下载为空");
        }
        List<Map<Integer, Object>> analyzeRes = EasyExcel.read(obsStream).sheet().headRowNumber(18).doReadSync();
//        log.info("=================================>analyzeRes数据为{}时间{}", JSON.toJSONString(analyzeRes), new Date());
        if (analyzeRes == null || analyzeRes.isEmpty()) {
            throw new CustomException("execl数据为空 请重新上传");
        }
        ArrayList<Map<String, Object>> errorArrayList = new ArrayList<>();
        Integer succCount = 0;
        Integer fullCount = 0;
        for (Map<Integer, Object> item : analyzeRes) {
            Map<String, Object> databaseFieldMap = convertToDatabaseFields(item);
            try {
                Date startDate = new Date();
                succCount = saveData(databaseFieldMap,map,succCount);
                Date endDate = new Date();
                long diffMilliseconds = endDate.getTime() - startDate.getTime();
            } catch (Exception e) {
                if (e instanceof CustomException) {
                    log.error("任务id{}当前行出现的数据问题{}时间{}", map.get("id"), e, new Date());
                } else {
                    log.error("任务id{}当前行出现的异常{}时间{}", map.get("id"), e, new Date());
                }
//                log.info("===================================>databaseFieldMap{}时间{}", JSON.toJSONString(databaseFieldMap), new Date());
                HashMap<String, Object> errorMap = new HashMap<>();
                errorMap.put("jobId", map.get("id"));
                errorMap.put("gardenName", databaseFieldMap.get("gardenName"));
                errorMap.put("residentialName", databaseFieldMap.get("residentialName"));
                errorMap.put("buildingName", databaseFieldMap.get("buildingName"));
                errorMap.put("unitName", databaseFieldMap.get("unitName"));
                errorMap.put("floorNum", databaseFieldMap.get("floorNum"));
                errorMap.put("doorplateNum", databaseFieldMap.get("doorplateNum"));
                errorMap.put("userName", databaseFieldMap.get("userName"));
                errorMap.put("sex", databaseFieldMap.get("sex"));
                errorMap.put("folk", databaseFieldMap.get("folk"));
                errorMap.put("cardno", databaseFieldMap.get("cardno"));
                errorMap.put("politicalOutlook", databaseFieldMap.get("politicalOutlook"));
                errorMap.put("livingCondition", databaseFieldMap.get("livingCondition"));
                errorMap.put("tel", databaseFieldMap.get("tel"));
                errorMap.put("hjAddress", databaseFieldMap.get("hjAddress"));
                errorMap.put("nowAddress", databaseFieldMap.get("nowAddress"));
                errorMap.put("relation", databaseFieldMap.get("relation"));
                errorMap.put("juzhuType", databaseFieldMap.get("juzhuType"));
                errorMap.put("hujiType", databaseFieldMap.get("hujiType"));
                errorMap.put("userType", databaseFieldMap.get("userType"));
                StringBuilder stringBuilder = new StringBuilder();
                if (Objects.nonNull(databaseFieldMap.get("flagOne"))&&StringUtils.isNotBlank((String) databaseFieldMap.get("flagOne"))) {
                    stringBuilder.append(databaseFieldMap.get("flagOne"));
                    errorMap.put("flagOne", databaseFieldMap.get("flagOne"));
                } else {
                    stringBuilder.append("0");
                    errorMap.put("flagOne", "");
                }
                stringBuilder.append(",");
                if (Objects.nonNull(databaseFieldMap.get("flagTwo"))&&StringUtils.isNotBlank((String) databaseFieldMap.get("flagTwo"))) {
                    stringBuilder.append(databaseFieldMap.get("flagTwo"));
                    errorMap.put("flagTwo", databaseFieldMap.get("flagTwo"));
                } else {
                    stringBuilder.append("0");
                    errorMap.put("flagTwo", "");
                }
                stringBuilder.append(",");
                if (Objects.nonNull(databaseFieldMap.get("flagThree"))&&StringUtils.isNotBlank((String) databaseFieldMap.get("flagThree"))) {
                    stringBuilder.append(databaseFieldMap.get("flagThree"));
                    errorMap.put("flagThree", databaseFieldMap.get("flagThree"));
                } else {
                    stringBuilder.append("0");
                    errorMap.put("flagThree", " ");
                }
                stringBuilder.append(",");
                if (Objects.nonNull(databaseFieldMap.get("flagFour"))&&StringUtils.isNotBlank((String) databaseFieldMap.get("flagFour"))) {
                    stringBuilder.append(databaseFieldMap.get("flagFour"));
                    errorMap.put("flagFour", databaseFieldMap.get("flagFour"));
                } else {
                    stringBuilder.append("0");
                    errorMap.put("flagFour", " ");
                }
                stringBuilder.append(",");
                if (Objects.nonNull(databaseFieldMap.get("flagFive"))&&StringUtils.isNotBlank((String) databaseFieldMap.get("flagFive"))) {
                    stringBuilder.append(databaseFieldMap.get("flagFive"));
                    errorMap.put("flagFive", databaseFieldMap.get("flagFive"));
                } else {
                    stringBuilder.append("0");
                    errorMap.put("flagFive", " ");
                }
                errorMap.put("keyFocusPersonnelType", stringBuilder.toString());
                if (Objects.nonNull(databaseFieldMap.get("remarks"))&&StringUtils.isNotBlank(String.valueOf(databaseFieldMap.get("remarks")))) {
                    errorMap.put("remarks", databaseFieldMap.get("remarks"));
                }
                if (e instanceof CustomException) {
                    errorMap.put("errorReasonDetail",e.getMessage());
                    errorMap.put("errorReason", e.getMessage());
                } else {
                    errorMap.put("errorReasonDetail",e.getMessage());
                    errorMap.put("errorReason", "系统内部异常或数据异常请联系管理员");
                }
                errorMap.put("createTime", new Date());
                commonService.insert(errorExeclNameSpace + "saveErrorExeclInfo", errorMap);
                fullCount++;
//                log.info("=======================================================>errorMap: " + JSON.toJSONString(errorMap));
                errorArrayList.add(errorMap);
//                log.info("=======================================================>errorMap: " + JSON.toJSONString(errorArrayList));

            }
        }
        HashMap<String, Integer> countHashMap = new HashMap<>();
        countHashMap.put("succCount", succCount);
        countHashMap.put("fullCount", fullCount);
        uploadFileExecl(errorArrayList, map);
        return countHashMap;
    }

    public Integer saveData(Map<String, Object> databaseFieldMap, HashMap<String,Object> map, Integer succCount) throws Exception {
        // 保存数据
        String officeId = String.valueOf(map.get("officeId"));
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("officeId", officeId);
        HashMap areaMap = commonService.getObject(officeSpace + "getAreaIdByOfficeId", hashMap);
//        log.info("areaMap>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + JSON.toJSONString(areaMap));
        String areaId = String.valueOf(areaMap.get("areaId"));
        String parentIds = String.valueOf(areaMap.get("parentIds"));
        String createBy = String.valueOf(map.get("createBy"));
        //处理网格
        if ((Objects.isNull(databaseFieldMap.get("gardenName"))|| StringUtils.isBlank(String.valueOf(databaseFieldMap.get("gardenName"))))) {
            throw new CustomException("网格名称为空");
        }
        String gardenName = String.valueOf(databaseFieldMap.get("gardenName"));
        if (gardenName.length()>40) {
            throw new CustomException("网格名称长度不能超过40！");
        }
        String garDenId = saveGarDenInfo(gardenName, parentIds, createBy, officeId);
        //处理小区
        if ((Objects.isNull(databaseFieldMap.get("residentialName"))|| StringUtils.isBlank(String.valueOf(databaseFieldMap.get("residentialName"))))) {
            throw new CustomException("小区名称为空");
        }
        String residentialName = String.valueOf(databaseFieldMap.get("residentialName"));
        if (residentialName.length()>40) {
            throw new CustomException("小区名称长度不能超过40！");
        }
        String residentialId = saveResidentialInfo(garDenId, residentialName, parentIds, createBy, officeId);
        //处理楼栋
        if ((Objects.isNull(databaseFieldMap.get("buildingName"))|| StringUtils.isBlank(String.valueOf(databaseFieldMap.get("buildingName"))))) {
            throw new CustomException("楼栋名称为空");
        }
        String buildingName = String.valueOf(databaseFieldMap.get("buildingName"));
        if (buildingName.length()>40) {
            throw new CustomException("楼栋名称长度不能超过40！");
        }
        String buildingId = saveBuildingInfo(garDenId, residentialId, buildingName, parentIds, createBy, officeId);
        //处理单元
        if ((Objects.isNull(databaseFieldMap.get("unitName"))|| StringUtils.isBlank(String.valueOf(databaseFieldMap.get("unitName"))))) {
            throw new CustomException("单元名称为空");
        }
        String unitName = String.valueOf(databaseFieldMap.get("unitName"));
        if (unitName.length()>40) {
            throw new CustomException("单元名称长度不能超过40！");
        }
        String unitId = saveUnitInfo(garDenId, residentialId, buildingId, unitName, parentIds, createBy, officeId);
        //处理楼层
        if ((Objects.isNull(databaseFieldMap.get("floorNum"))|| StringUtils.isBlank(String.valueOf(databaseFieldMap.get("floorNum"))))) {
            throw new CustomException("楼层名称为空");
        }
        String floorNum = String.valueOf(databaseFieldMap.get("floorNum"));//
        if (floorNum.length()>40) {
            throw new CustomException("楼层名称长度不能超过40！");
        }
        vaildNum(0, floorNum);
        String floorId = savefloorInfo(garDenId, residentialId, buildingId, unitId, floorNum, parentIds, createBy, officeId);
        //处理户
        //校验楼层数据合法性
        if ((Objects.isNull(databaseFieldMap.get("doorplateNum"))|| StringUtils.isBlank(String.valueOf(databaseFieldMap.get("doorplateNum"))))) {
            throw new CustomException("户名称为空");
        }
        String doorplateNum = String.valueOf(databaseFieldMap.get("doorplateNum"));
        if (doorplateNum.length()>40) {
            throw new CustomException("户名称长度不能超过40！");
        }
        //验证户合法性
        vaildNum(1, doorplateNum);
        String doorplateId = saveDoorplate(garDenId, residentialId, buildingId, unitId, floorId, doorplateNum, parentIds, createBy, officeId);
        //处理居民
        vaildAndSavePerson(databaseFieldMap, garDenId, residentialId, buildingId, unitId, floorId, doorplateId, parentIds, createBy, officeId);
        succCount++;
        TimeUnit.MILLISECONDS.sleep(100);
        return succCount;
    }
    public void uploadFileExecl(List<Map<String, Object>> errorArrayList, HashMap<String, Object> map) {
        if (!CollectionUtils.isEmpty(errorArrayList)) {
            // 创建字节数组输出流（内存中存储 Excel 数据）
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//            log.info("");
            // 使用 EasyExcel 写入流
            EasyExcel.write(outputStream)
                    .head(getHead()) // 设置表头
                    .sheet("问题数据") // 工作表名称
                    .doWrite(convertData(errorArrayList)); // 写入数据

            // 将输出流转换为输入流（便于后续读取或传输）
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(outputStream.toByteArray());
            String fileUuid = UUID.randomUUID().toString();
            PutObjectRequest request = new PutObjectRequest(bucketName, fileUuid);
            PutObjectResult putObjectResult = null;
            Map<String, Object> returnMap = new HashMap<>();
            try {
                request.setInput(byteArrayInputStream);
                putObjectResult = obsClient.putObject(request);
                String objectUrl = putObjectResult.getObjectUrl();
                //替换obs下载地址ip
                Pattern pattern = Pattern.compile("/");
                Matcher findMatcher = pattern.matcher(objectUrl);
                int number = 0;
                while (findMatcher.find()) {
                    number++;
                    //当“/”第二次出现时停止
                    if (number == 3) {
                        break;
                    }
                }
                int i = findMatcher.start();
                String downloadUrl = showPoint + objectUrl.substring(i);
                returnMap.put("id", map.get("id"));
                returnMap.put("errorObsKey", fileUuid);
                returnMap.put("errorObsUrl", downloadUrl);
                returnMap.put("updateTime", new Date());
                commonService.update(nameSpace + "updateFileTask", returnMap);
            } catch (Exception e) {
               log.error("上传文件异常{}时间{}", e, new Date());
                returnMap.put("id", map.get("id"));
                returnMap.put("errorObsUploadFailReason", e.toString());
                returnMap.put("updateTime", new Date());
                commonService.update(nameSpace + "updateFileTask", returnMap);
            }
        }else {
            log.info("不存在异常数据");
        }

    }

    public void vaildAndSavePerson(Map<String, Object> databaseFieldMap, String garDenId, String residentialId, String buildingId, String unitId, String floorId, String doorplateId, String parentIds, String createBy, String officeId) throws Exception {
        HashMap<String, Object> map = new HashMap<>();
        if (Objects.isNull(databaseFieldMap.get("userName"))||StringUtils.isBlank((String) databaseFieldMap.get("userName"))) {
            throw new CustomException("姓名不能为空");
        }
        if (EmojiFilterUtils.containsEmoji((String) databaseFieldMap.get("userName"))) {
            throw new CustomException("姓名中不能添加表情");
        }
        if (String.valueOf(databaseFieldMap.get("userName")).length() > 20) {
            throw new CustomException("姓名长度不能超过20");
        }
        map.put("user_name", databaseFieldMap.get("userName"));
        if (Objects.isNull(databaseFieldMap.get("sex"))||StringUtils.isBlank((String) databaseFieldMap.get("sex"))) {
            throw new CustomException("性别不能为空");
        }
        switch ((String) databaseFieldMap.get("sex")) {
            case "男":
                map.put("sex", 1);
                break;
            case "女":
                map.put("sex", 2);
                break;
            default:
                throw new CustomException("性别应添男女选项");
        }
        if (Objects.isNull(databaseFieldMap.get("folk"))||StringUtils.isBlank(String.valueOf(databaseFieldMap.get("folk")))) {
            throw new CustomException("民族不能为空");
        }
        String folk = commonService.getObject(userNameSpace + "findFolkCodeByName", String.valueOf(databaseFieldMap.get("folk")));
        if (StringUtils.isBlank(folk)) {
            throw new CustomException("请按照表选项进行填写民族选项");
        } else {
            map.put("folk", folk);
        }
        if (Objects.isNull(databaseFieldMap.get("cardno"))||StringUtils.isBlank(String.valueOf(databaseFieldMap.get("cardno")))) {
            throw new CustomException("身份证号不能为空");
        }
        String cardno = String.valueOf(databaseFieldMap.get("cardno")).trim();
        if (!IdcardUtil.isValidCard(cardno)) {
            throw new CustomException("身份证号不合法！");
        }
        Integer count = commonService.getObject(userNameSpace + "getGridUserByCardNoCount", cardno);
        if (count.compareTo(0)!=0) {
            throw new CustomException("当前人员已存在！");
        }
        map.put("cardno", databaseFieldMap.get("cardno"));
        //默认身份证
        map.put("cardType", "1");
        if (Objects.nonNull(databaseFieldMap.get("politicalOutlook"))||StringUtils.isNotBlank(String.valueOf(databaseFieldMap.get("politicalOutlook")))) {
            int politicalOutlook = PoliticalStatusEnum.getCodeByDescription(String.valueOf(databaseFieldMap.get("politicalOutlook")));
            map.put("political_outlook", politicalOutlook);
        }
        if (Objects.isNull(databaseFieldMap.get("livingCondition"))||StringUtils.isBlank(String.valueOf(databaseFieldMap.get("livingCondition")))) {
            throw new CustomException("居住方式不能为空");
        }
        int livingCondition = HousingType.getCodeByDescription(String.valueOf(databaseFieldMap.get("livingCondition")));
        if (livingCondition == -1) {
            throw new CustomException("请按照提示填写居住方式");
        }
        map.put("living_condition", HousingType.getCodeByDescription(String.valueOf(databaseFieldMap.get("livingCondition"))));
        if (Objects.isNull(databaseFieldMap.get("tel"))||StringUtils.isBlank(String.valueOf(databaseFieldMap.get("tel")))) {
            throw new CustomException("联系方式不能为空");
        }
        if (!isValidPhone(String.valueOf(databaseFieldMap.get("tel")))) {
            throw new CustomException("联系方式格式不正确");
        }
        map.put("tel", databaseFieldMap.get("tel"));
        if (Objects.isNull(databaseFieldMap.get("hjAddress"))||StringUtils.isBlank(String.valueOf(databaseFieldMap.get("hjAddress")))) {
            throw new CustomException("户籍地址不能为空");
        }
        if (String.valueOf(databaseFieldMap.get("hjAddress")).length() > 150) {
            throw new CustomException("户籍地址长度不能超过150个字");
        }
        map.put("hj_address", databaseFieldMap.get("hjAddress"));
        if (Objects.isNull(databaseFieldMap.get("nowAddress"))||StringUtils.isBlank(String.valueOf(databaseFieldMap.get("nowAddress")))) {
            throw new CustomException("现地址不能为空");
        }
        if (String.valueOf(databaseFieldMap.get("nowAddress")).length() > 150) {
            throw new CustomException("现地址长度不能超过150个字");
        }
        map.put("now_address", databaseFieldMap.get("nowAddress"));
        if (Objects.isNull(databaseFieldMap.get("relation"))||StringUtils.isBlank(String.valueOf(databaseFieldMap.get("relation")))) {
            throw new CustomException("与户主关系不能为空");
        }
        int relation = FamilyRelationshipEnum.fromDescription(String.valueOf(databaseFieldMap.get("relation"))).getCode();
        map.put("relation", relation);
        if (Objects.isNull(databaseFieldMap.get("juzhuType"))||StringUtils.isBlank(String.valueOf(databaseFieldMap.get("juzhuType")))) {
            throw new CustomException("居住情况不能为空");
        }
        switch (String.valueOf(databaseFieldMap.get("juzhuType"))) {
            case "居住":
                map.put("juzhu_type", 0);
                break;
            case "非居住":
                map.put("juzhu_type", 1);
                break;
            default:
                throw new CustomException("居住情况填写不正确");
        }
        if (Objects.isNull(databaseFieldMap.get("hujiType"))||StringUtils.isBlank(String.valueOf(databaseFieldMap.get("hujiType")))) {
            throw new CustomException("是否户籍不能为空");
        }
        switch (String.valueOf(databaseFieldMap.get("hujiType"))) {
            case "是户籍地址":
                map.put("huji_type", 0);
                break;
            case "非户籍地址":
                map.put("huji_type", 1);
                break;
            default:
                throw new CustomException("是否户籍填写不正确");
        }
        if (Objects.isNull(databaseFieldMap.get("userType"))||StringUtils.isBlank(String.valueOf(databaseFieldMap.get("userType")))) {
            throw new CustomException("人口类型不能为空");
        }
        switch (String.valueOf(databaseFieldMap.get("userType"))) {
            case "常驻人口":
                map.put("user_type", 0);
                break;
            case "流动人口":
                map.put("user_type", 1);
                break;
            default:
                throw new CustomException("人口类型填写不正确");
        }
        ArrayList<HashMap<String, Object>> hashMaps = new ArrayList<>();
        if (Objects.nonNull(databaseFieldMap.get("flagOne"))&&StringUtils.isNotBlank(String.valueOf(databaseFieldMap.get("flagOne")))) {
            Map<String, Object> typeMap = commonService.getObject(focusgroupNameSpace + "GetGridFocusGroupTypeList", String.valueOf(databaseFieldMap.get("flagOne")));
            if (CollectionUtils.isEmpty(typeMap)) {
                throw new CustomException("标签一值不正确请按表格提示添加数据");
            }
            HashMap<String, Object> typeParamMap = new HashMap<>();
            typeParamMap.put("cardno", String.valueOf(databaseFieldMap.get("cardno")));
            typeParamMap.put("lable_id", typeMap.get("id"));
            typeParamMap.put("createBy", createBy);
            hashMaps.add(typeParamMap);
        }
        if (Objects.nonNull(databaseFieldMap.get("flagTwo"))&&StringUtils.isNotBlank(String.valueOf(databaseFieldMap.get("flagTwo")))) {
            Map<String, Object> typeMap = commonService.getObject(focusgroupNameSpace + "GetGridFocusGroupTypeList", String.valueOf(databaseFieldMap.get("flagTwo")));
            if (CollectionUtils.isEmpty(typeMap)) {
                throw new CustomException("标签二值不正确请按表格提示添加数据");
            }
            HashMap<String, Object> typeParamMap = new HashMap<>();
            typeParamMap.put("cardno", String.valueOf(databaseFieldMap.get("cardno")));
            typeParamMap.put("lable_id", typeMap.get("id"));
            typeParamMap.put("createBy", createBy);
            hashMaps.add(typeParamMap);
        }
        if (Objects.nonNull(databaseFieldMap.get("flagThree"))&&StringUtils.isNotBlank(String.valueOf(databaseFieldMap.get("flagThree")))) {
            Map<String, Object> typeMap = commonService.getObject(focusgroupNameSpace + "GetGridFocusGroupTypeList", String.valueOf(databaseFieldMap.get("flagThree")));
            if (CollectionUtils.isEmpty(typeMap)) {
                throw new CustomException("标签三值不正确请按表格提示添加数据");
            }
            HashMap<String, Object> typeParamMap = new HashMap<>();
            typeParamMap.put("cardno", String.valueOf(databaseFieldMap.get("cardno")));
            typeParamMap.put("lable_id", typeMap.get("id"));
            typeParamMap.put("createBy", createBy);
            hashMaps.add(typeParamMap);
        }
        if (Objects.nonNull(databaseFieldMap.get("flagFour"))&&StringUtils.isNotBlank(String.valueOf(databaseFieldMap.get("flagFour")))) {
            Map<String, Object> typeMap = commonService.getObject(focusgroupNameSpace + "GetGridFocusGroupTypeList", String.valueOf(databaseFieldMap.get("flagFour")));
            if (CollectionUtils.isEmpty(typeMap)) {
                throw new CustomException("标签四值不正确请按表格提示添加数据");
            }
            HashMap<String, Object> typeParamMap = new HashMap<>();
            typeParamMap.put("cardno", String.valueOf(databaseFieldMap.get("cardno")));
            typeParamMap.put("lable_id", typeMap.get("id"));
            typeParamMap.put("createBy", createBy);
            hashMaps.add(typeParamMap);
        }
        if (Objects.nonNull(databaseFieldMap.get("flagFive"))&&StringUtils.isNotBlank(String.valueOf(databaseFieldMap.get("flagFive")))) {
            Map<String, Object> typeMap = commonService.getObject(focusgroupNameSpace + "GetGridFocusGroupTypeList", String.valueOf(databaseFieldMap.get("flagFive")));
            if (CollectionUtils.isEmpty(typeMap)) {
                throw new CustomException("标签五值不正确请按表格提示添加数据");
            }
            HashMap<String, Object> typeParamMap = new HashMap<>();
            typeParamMap.put("cardno", String.valueOf(databaseFieldMap.get("cardno")));
            typeParamMap.put("lable_id", typeMap.get("id"));

            typeParamMap.put("createBy", createBy);
            hashMaps.add(typeParamMap);
        }
        List<HashMap<String, Object>> collect = hashMaps.stream()
                .collect(Collectors.groupingBy(e -> e, Collectors.counting()))
                .entrySet().stream()
                .filter(e -> e.getValue() > 1)
                .map(Map.Entry::getKey)
                .collect(Collectors.toList());
//        log.info("collect>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + JSON.toJSONString(collect));
        if (!CollectionUtils.isEmpty(collect)) {
            throw new CustomException("标签存在重复");
        }
        if (Objects.nonNull(databaseFieldMap.get("remarks"))&&StringUtils.isNotBlank(String.valueOf(databaseFieldMap.get("remarks")))) {
            if (String.valueOf(databaseFieldMap.get("remarks")).length() > 200) {
                throw new CustomException("备注长度不能超过200个字");
            }
            map.put("remarks",databaseFieldMap.get("remarks"));
        }
        String[] parentIdArray = parentIds.split(",");
        map.put("city_id", parentIdArray[2]);
        map.put("area_id", parentIdArray[3]);
        map.put("street_id", parentIdArray[4]);
        map.put("community_id", officeId);
        String communityCode = commonService.getObject(communityNameSpace + "getcommunityCode", officeId);
        map.put("community_code", communityCode);
        map.put("garden_id", garDenId);
        map.put("residentialId", residentialId);
        map.put("building_id", buildingId);
        map.put("unit_id", unitId);
        map.put("floor_id", floorId);
        map.put("doorplate_id", doorplateId);
        map.put("create_by", createBy);
        map.put("dataSource",2);
        RLock lock = redissonClient.getLock("zfw:GirdUserImprotJobTask"+"12:" + doorplateId + ";" + (String) databaseFieldMap.get("userName"));
        try {
            if (lock.tryLock(30,TimeUnit.SECONDS)) {
//                TimeUnit.MILLISECONDS.sleep(100);
                commonService.insert(userNameSpace + "insertUserGridForTask", map);
                hashMaps.forEach(v -> {
                    commonService.insert(userNameSpace + "insertFocusGroupForTask", v);
                });
            }
        } catch (Exception e) {
            log.error("新增居民为{}异常{}时间{}", (String) databaseFieldMap.get("userName"), e, new Date());
            throw e;
        } finally {
            lock.unlock();
        }
    }

    /**
     * 验证输入的字符串是否为合法的手机号或座机号
     *
     * @param phone 待验证的字符串
     * @return 如果是合法的手机号或座机号返回true，否则返回false
     */
    public boolean isValidPhone(String phone) {
        if (phone == null || phone.trim().isEmpty()) {
            return false;
        }
        return phone.matches(PHONE_REGEX);
    }

    /**
     * @param garDenId
     * @param residentialId
     * @param buildingId
     * @param unitId
     * @param floorId
     * @param doorplateNum
     * @param parentIds
     * @param createBy
     * @param officeId
     * @return
     */
    public String saveDoorplate(String garDenId, String residentialId, String buildingId, String unitId, String floorId, String doorplateNum, String parentIds, String createBy, String officeId) throws InterruptedException {
        RLock lock = redissonClient.getLock("zfw:GirdUserImprotJobTask"+"12:" + floorId + ";" + doorplateNum);
        String doorplateId = null;
        try {
            if (lock.tryLock(30, TimeUnit.SECONDS)) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("floorId", floorId);
                map.put("doorplateNum", doorplateNum);
                doorplateId = commonService.getObject(doorplateNameSpace + "getDoorplateId", map);
                if (StringUtils.isEmpty(doorplateId)) {
                    String[] parentIdArray = parentIds.split(",");
                    String communityCode = commonService.getObject(communityNameSpace + "getcommunityCode", officeId);
                    doorplateId = UUID.randomUUID().toString();
                    HashMap<String, Object> paramMap = new HashMap<>();
                    paramMap.put("id", doorplateId);
                    paramMap.put("name", doorplateNum);
                    BigDecimal sort = commonService.getObject(doorplateNameSpace + "getSort", floorId);
                    BigDecimal thisSort = null;
                    if (sort == null) {
                        thisSort = BigDecimal.valueOf(1);
                    } else {
                        thisSort = sort.add(BigDecimal.valueOf(1));
                    }
                    paramMap.put("sort", thisSort);
                    paramMap.put("companyCode", communityCode);
                    paramMap.put("cityId", parentIdArray[2]);
                    paramMap.put("areaId", parentIdArray[3]);
                    paramMap.put("streetId", parentIdArray[4]);
                    paramMap.put("communityId", officeId);
                    paramMap.put("gardenId", garDenId);
                    paramMap.put("residentialId", residentialId);
                    paramMap.put("buildingId", buildingId);
                    paramMap.put("unitId", unitId);
                    paramMap.put("floorId", floorId);
                    paramMap.put("grade", 11);
                    paramMap.put("createBy", String.valueOf(createBy));
                    paramMap.put("createTime", new Date());
                    paramMap.put("delFlag", 0);
                    paramMap.put("dataSource",2);
//                    TimeUnit.MILLISECONDS.sleep(100);
                    commonService.insert(doorplateNameSpace + "saveDoorplateInfo", paramMap);
                }

            }
        } catch (Exception e) {
            log.error("新增户为{}异常{}时间{}", doorplateNum, e, new Date());
            throw e;
        } finally {
            lock.unlock();
        }
        return doorplateId;

    }

    /**
     * 校验数字数据合法性
     *
     * @param type
     * @param num
     */
    public static void vaildNum(Integer type, String num) {
        try {
            StringUtils.toInteger(num);
        } catch (Exception e) {
            switch (type) {
                case 0:
                    throw new CustomException("楼层必须为数字");
                case 1:
                    throw new CustomException("户必须为数字");
                default:
                    throw new CustomException("数据异常");
            }
        }
    }

    /**
     * @param garDenId
     * @param residentialId
     * @param buildingId
     * @param unitId
     * @param floorNum
     * @param parentIds
     * @param createBy
     * @param officeId
     * @return
     */
    private String savefloorInfo(String garDenId, String residentialId, String buildingId, String unitId, String floorNum, String parentIds, String createBy, String officeId) throws InterruptedException {
        RLock lock = redissonClient.getLock("zfw:GirdUserImprotJobTask"+"11:" + unitId + ";" + floorNum);
        String floorId = null;
        try {
            if (lock.tryLock(30, TimeUnit.SECONDS)) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("unitId", unitId);
                map.put("floorNum", floorNum);
                floorId= commonService.getObject(floorNameSpace + "getFloorId", map);
                if (StringUtils.isEmpty(floorId)) {
                    String[] parentIdArray = parentIds.split(",");
                    String communityCode = commonService.getObject(communityNameSpace + "getcommunityCode", officeId);
                    floorId = UUID.randomUUID().toString();
                    HashMap<String, Object> paramMap = new HashMap<>();
                    paramMap.put("id", floorId);
                    paramMap.put("name", floorNum);
                    BigDecimal sort = commonService.getObject(floorNameSpace + "getSort", unitId);
                    BigDecimal thisSort = null;
                    if (sort == null) {
                        thisSort = BigDecimal.valueOf(1);
                    } else {
                        thisSort = sort.add(BigDecimal.valueOf(1));
                    }
                    paramMap.put("sort", thisSort);
                    paramMap.put("companyCode", communityCode);
                    paramMap.put("cityId", parentIdArray[2]);
                    paramMap.put("areaId", parentIdArray[3]);
                    paramMap.put("streetId", parentIdArray[4]);
                    paramMap.put("communityId", officeId);
                    paramMap.put("gardenId", garDenId);
                    paramMap.put("residentialId", residentialId);
                    paramMap.put("buildingId", buildingId);
                    paramMap.put("unitId", unitId);
                    paramMap.put("grade", 10);
                    paramMap.put("createBy", String.valueOf(createBy));
                    paramMap.put("createTime", new Date());
                    paramMap.put("delFlag", 0);
                    paramMap.put("dataSource",2);
//                    TimeUnit.MILLISECONDS.sleep(100);
                    commonService.insert(floorNameSpace + "saveFloorInfo", paramMap);
                }

            }
        } catch (Exception e) {
            log.error("新增楼层为{}异常{}时间{}", floorNum, e, new Date());
            throw e;
        } finally {
            lock.unlock();
        }
        return floorId;
    }

    /**
     * @param residentialId
     * @param buildingId
     * @param unitName
     * @param parentIds
     * @param createBy
     * @param officeId
     * @return
     */
    private String saveUnitInfo(String garDenId, String residentialId, String buildingId, String unitName, String parentIds, String createBy, String officeId) throws InterruptedException {

        RLock lock = redissonClient.getLock("zfw:GirdUserImprotJobTask"+"10:" + buildingId + ";" + unitName);
        String unitId = null;
        try {
            if (lock.tryLock(30, TimeUnit.SECONDS)) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("buildingId", buildingId);
                map.put("unitName", unitName);
                unitId = commonService.getObject(unitNameSpace + "queryUnitId", map);
                if (StringUtils.isEmpty(unitId)) {
                    String[] parentIdArray = parentIds.split(",");
                    String communityCode = commonService.getObject(communityNameSpace + "getcommunityCode", officeId);
                    unitId = UUID.randomUUID().toString();
                    HashMap<String, Object> paramMap = new HashMap<>();
                    paramMap.put("id", unitId);
                    paramMap.put("name", unitName);
                    paramMap.put("companyCode", communityCode);
                    paramMap.put("cityId", parentIdArray[2]);
                    paramMap.put("areaId", parentIdArray[3]);
                    paramMap.put("streetId", parentIdArray[4]);
                    paramMap.put("communityId", officeId);
                    paramMap.put("gardenId", garDenId);
                    paramMap.put("residentialId", residentialId);
                    paramMap.put("buildingId", buildingId);
                    paramMap.put("grade", 9);
                    paramMap.put("createBy", String.valueOf(createBy));
                    paramMap.put("createTime", new Date());
                    paramMap.put("delFlag", 0);
                    paramMap.put("dataSource",2);
//                    TimeUnit.MILLISECONDS.sleep(100);
                    commonService.insert(unitNameSpace + "saveUnitInfo", paramMap);
                }

            }
        } catch (Exception e) {
            log.error("新增单元为{}异常{}时间{}", unitName, e, new Date());
            throw e;
        } finally {
            lock.unlock();
        }
        return unitId;

    }

    /**
     * @param garDenId
     * @param residentialId
     * @param buildingName
     * @param parentIds
     * @param createBy
     * @return
     */
    public String saveBuildingInfo(String garDenId, String residentialId, String buildingName, String parentIds, String createBy, String officeId) throws InterruptedException {
        RLock lock = redissonClient.getLock("zfw:GirdUserImprotJobTask"+"9:" + residentialId + ";" + buildingName);
        String buildingId = null;
        try {
            if (lock.tryLock(30, TimeUnit.SECONDS)) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("residentialId", residentialId);
                map.put("buildingName", buildingName);
                buildingId = commonService.getObject(buildingNameSpace + "getBuildingId", map);
                if (StringUtils.isEmpty(buildingId)) {
                    String[] parentIdArray = parentIds.split(",");
                    String communityCode = commonService.getObject(communityNameSpace + "getcommunityCode", officeId);
                    buildingId = UUID.randomUUID().toString();
                    HashMap<String, Object> paramMap = new HashMap<>();
                    paramMap.put("id", buildingId);
                    paramMap.put("name", buildingName);
                    paramMap.put("companyCode", communityCode);
                    paramMap.put("cityId", parentIdArray[2]);
                    paramMap.put("areaId", parentIdArray[3]);
                    paramMap.put("streetId", parentIdArray[4]);
                    paramMap.put("communityId", officeId);
                    paramMap.put("gardenId", garDenId);
                    paramMap.put("residentialId", residentialId);
                    paramMap.put("grade", 9);
                    paramMap.put("delFlag", 0);
                    paramMap.put("createBy", String.valueOf(createBy));
                    paramMap.put("createTime", new Date());
                    paramMap.put("dataSource",2);
//                    TimeUnit.MILLISECONDS.sleep(100);
                    commonService.insert(buildingNameSpace + "saveBuildingInfo", paramMap);
                }

            }
        } catch (Exception e) {
            log.error("新增楼栋为{}异常{}时间{}", buildingName, e, new Date());
            throw e;
        } finally {
            lock.unlock();
        }
        return buildingId;


    }

    /**
     * 处理小区 不可对外暴露
     *
     * @param garDenId
     * @param residentialName
     * @param parentIds
     * @param createBy
     * @return
     */
    public String saveResidentialInfo(String garDenId, String residentialName, String parentIds, String createBy, String officeId) throws InterruptedException {
        RLock lock = redissonClient.getLock("zfw:GirdUserImprotJobTask"+"8:" + garDenId + ";" + residentialName);
        String residentialId = null;
        try {
            if (lock.tryLock(30, TimeUnit.SECONDS)) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("garDenId", garDenId);
                map.put("residentialName", residentialName);
                residentialId = commonService.getObject(residentialNameSpace + "getResidentialIdByResidentialNameAndGardenId", map);
                if (StringUtils.isEmpty(residentialId)) {
                    residentialId = UUID.randomUUID().toString();
                    HashMap<String, Object> paramMap = new HashMap<>();
                    paramMap.put("id", residentialId);
                    paramMap.put("name", residentialName);
                    String[] parentIdArray = parentIds.split(",");
                    paramMap.put("cityId", parentIdArray[2]);
                    paramMap.put("areaId", parentIdArray[3]);
                    paramMap.put("streetId", parentIdArray[4]);
                    paramMap.put("communityId", officeId);
                    String communityCode = commonService.getObject(communityNameSpace + "getcommunityCode", officeId);
                    paramMap.put("companyCode", communityCode);
                    paramMap.put("gardenId", garDenId);
                    paramMap.put("grade", 8);
                    paramMap.put("createBy", String.valueOf(createBy));
                    paramMap.put("createTime", new Date());
                    paramMap.put("dataSource",2);
//                    TimeUnit.MILLISECONDS.sleep(100);
                    commonService.insert(residentialNameSpace + "saveResidentialinfo", paramMap);
                }

            }
        } catch (Exception e) {
            log.error("新增小区为{}异常{}时间{}", residentialName, e, new Date());
            throw e;
        } finally {
            lock.unlock();
        }
        return residentialId;
    }

    private static Map<String, Object> convertToDatabaseFields(Map<Integer, Object> map) {
        Map<String, Object> databaseFieldMap = new HashMap<>();
        map.forEach((key, value) -> {

            String databaseField = mapKeyToDatabaseField(key);
            databaseFieldMap.put(databaseField, value);
        });
        return databaseFieldMap;
    }

    /**
     * 创建表头
     */
    private List<List<String>> getHead() {
        ArrayList<List<String>> lists = new ArrayList<>();
        String headers = "*网格名称,*小区名称,*楼名称,*单元名称,*层数,*户名称（房间号）,*姓名,*性别,*民族,*身份证号,政治面貌,*居住方式,*联系方式,*户籍地址,*现住地址,*与户主关系,*居住情况,*是否户籍,*人口类型,标签1,标签2,标签3,标签4,标签5,备注,异常原因";
        List<String> headerList = Arrays.asList(headers.split(","));
        for (String header : headerList) {
            lists.add(Collections.singletonList(header));
        }
        return lists;
    }

    /**
     * 转换数据格式
     */
    private static List<List<Object>> convertData(List<Map<String, Object>> dataList) {
        List<List<Object>> content = new ArrayList<>();
        for (Map<String, Object> data : dataList) {
            List<Object> row = new ArrayList<>();
            // 按表头顺序添加数据
            for (String field : FIELD_NAMES) {
                row.add(data.getOrDefault(field, ""));
            }
            content.add(row);
        }
//        log.info("=======================================================>content: " + JSON.toJSONString(content));
        return content;
    }

    /**
     * 处理网格 不可对外暴露
     *
     * @param gardenName
     * @param parentIds
     * @param createBy
     * @return
     */
    public String saveGarDenInfo( String gardenName, String parentIds, String createBy, String officeId) throws InterruptedException {
        RLock lock = redissonClient.getLock("zfw:GirdUserImprotJobTask"+"7:" + officeId + ";" + gardenName);
        String id = null;
        try {
            if (lock.tryLock(30, TimeUnit.SECONDS)) {
                HashMap<String, Object> paramMap = new HashMap<>();
                paramMap.put("officeId", officeId);
                paramMap.put("gardenName", gardenName);
//                log.info("officeId是》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》{}",officeId);
//                log.info("gardenName是》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》{}",gardenName);
                id = commonService.getObject(gardenNameSpace + "getGardenId", paramMap);
//                log.info("网格id是》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》{}",id);
                if (StringUtils.isEmpty(id)) {
                    id = UUID.randomUUID().toString();
                    HashMap<String, Object> gardenParamMap = new HashMap<>();
                    gardenParamMap.put("id", id);
                    gardenParamMap.put("name", gardenName);
                    String[] parentIdArray = parentIds.split(",");
                    gardenParamMap.put("cityId", parentIdArray[2]);
                    gardenParamMap.put("areaId", parentIdArray[3]);
                    gardenParamMap.put("streetId", parentIdArray[4]);
                    gardenParamMap.put("communityId", officeId);
                    String communityCode = commonService.getObject(communityNameSpace + "getcommunityCode", officeId);
                    paramMap.put("companyCode", communityCode);
                    gardenParamMap.put("delFlag", 0);
                    gardenParamMap.put("createby", String.valueOf(createBy));
                    gardenParamMap.put("createTime", new Date());
                    gardenParamMap.put("dataSource",2);
//                    TimeUnit.MILLISECONDS.sleep(100);
                    commonService.insert(gardenNameSpace + "insertInfo", gardenParamMap);
                }
            }
        } catch (Exception e) {
            log.error("新增网格为{}异常{}时间{}", gardenName, e, new Date());
            throw e;
        } finally {
            lock.unlock();
        }
        return id;
    }

    private static String mapKeyToDatabaseField(int key) {
        switch (key) {
            case 0:
                return "gardenName";
            case 1:
                return "residentialName";
            case 2:
                return "buildingName";
            case 3:
                return "unitName";
            case 4:
                return "floorNum";
            case 5:
                return "doorplateNum";
            case 6:
                return "userName";
            case 7:
                return "sex";
            case 8:
                return "folk";
            case 9:
                return "cardno";
            case 10:
                return "politicalOutlook";
            case 11:
                return "livingCondition";
            case 12:
                return "tel";
            case 13:
                return "hjAddress";
            case 14:
                return "nowAddress";
            case 15:
                return "relation";
            case 16:
                return "juzhuType";
            case 17:
                return "hujiType";
            case 18:
                return "userType";
            case 19:
                return "flagOne";
            case 20:
                return "flagTwo";
            case 21:
                return "flagThree";
            case 22:
                return "flagFour";
            case 23:
                return "flagFive";
            case 24:
                return "remarks";
            default:
                return "";
        }
    }


    @ApiOperation(value = "execl任务测试", desc = "execl任务测试", nologin = true)
    public void girdUserImprotJob() {
        RLock rLock = redissonClient.getLock("zfw:GirdUserImprotJobTask");
        HashMap<String, Object> map = null;
        try {
            if (rLock.tryLock(10, TimeUnit.SECONDS)) {
                map = commonService.getObject(nameSpace + "findFirstOne", null);
                if (!CollectionUtils.isEmpty(map)) {
                    HashMap<String, Object> updateMap = new HashMap<>();
                    updateMap.put("id", map.get("id"));
                    updateMap.put("jobStatus", 1);
                    updateMap.put("dealResultmessage", "您导入的数据正在处理中，请稍后");
                    updateMap.put("dealTime", new Date());
                    updateMap.put("updateTime", new Date());
                    commonService.update(nameSpace + "updateFileTask", updateMap);
                    HashMap<String, Integer> countHashMap = GirdUserImprotJobTask(map);
                    HashMap<String, Object> endupdateMap = new HashMap<>();
                    endupdateMap.put("id", map.get("id"));
                    endupdateMap.put("jobStatus", 2);
                    Integer fullCount = countHashMap.get("fullCount");
                    Integer succCount = countHashMap.get("succCount");
                    int count = succCount + fullCount;
                    if (fullCount.compareTo(count) == 0) {
                        endupdateMap.put("dealResult", 0);
                        endupdateMap.put("dealResultMessage", "您共导入" + count + "条数据 成功：" + succCount + "条，失败：" + fullCount + "条");
                    } else if (fullCount.compareTo(0) == 0) {
                        endupdateMap.put("dealResult", 1);
                        endupdateMap.put("dealResultMessage", "您共导入" + count + "条数据 成功：" + succCount + "条，失败：" + fullCount + "条");
                    } else {
                        endupdateMap.put("dealResult", 2);
                        endupdateMap.put("dealResultMessage", "您共导入" + count + "条数据 成功：" + succCount + "条，失败：" + fullCount + "条");
                    }
                    endupdateMap.put("update_time", new Date());
                    commonService.update(nameSpace + "updateFileTask", endupdateMap);

                } else {
                    log.info("人员导入定时任务未有需要处理的点");
                }
            } else {
                log.info("人员导入定时任务正在处理。。。");
            }
        } catch (Exception e) {
            UnifyLogger.parent(UnifyLogger.getTrace(e), UnifyLogger.Level.INFO);
            HashMap<String, Object> updateMap = new HashMap<>();
            updateMap.put("id", map.get("id"));
            updateMap.put("orginalObsDownloadFailReason", e.toString());
            updateMap.put("jobStatus", 2);
            updateMap.put("dealResult", 3);
            updateMap.put("updateTime", new Date());
            if (e instanceof CustomException) {
                updateMap.put("dealResultMessage", "您导入的数据失败:" + e.getMessage());
            } else {
                updateMap.put("dealResultMessage", "您导入的数据失败");
            }
            commonService.update(nameSpace + "updateFileTask", updateMap);
        } finally {
            rLock.unlock();
        }
    }

    public static void main(String[] args) {
        System.out.println(IdcardUtil.isValidCard("220821201105244528"));
        String date = DateUtils.convertDate2String(DateUtil.YEAR_MONTH_DAY_PATTERN, new Date());
        long currentTimeMillis = System.currentTimeMillis();
        System.out.println("userImport:" + date + ":" + currentTimeMillis);
       vaildNum(0, "a1");
        StringUtils.toInteger("a1");

    }
}
