package com.boman.web.core.service.vaccineInfo.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.boman.common.core.utils.DateUtils;
import com.boman.common.core.utils.SecurityUtils;
import com.boman.common.core.utils.StringUtils;
import com.boman.common.core.utils.number.NumberUtils;
import com.boman.common.core.utils.sql.SqlUtil;
import com.boman.common.core.web.page.PageDomain;
import com.boman.common.core.web.page.TableSupport;
import com.boman.common.redis.service.RedisService;
import com.boman.domain.*;
import com.boman.domain.dto.AjaxResult;
import com.boman.domain.utils.ThreadPoolService;
import com.boman.system.api.RemoteDeptService;
import com.boman.system.api.RemoteDictDataService;
import com.boman.web.core.mapper.StandardlyMapper;
import com.boman.web.core.mapper.VaccineInfoMapper;
import com.boman.web.core.mapper.VaccineInfoOperationMapper;
import com.boman.web.core.mapper.VaccineInfoUserMapper;
import com.boman.web.core.service.save.IBaseSaveService;
import com.boman.web.core.service.vaccineInfo.IVaccineInfoService;
import com.boman.web.core.utils.AuthUtils;
import com.boman.web.core.utils.IdUtils;
import com.boman.web.core.utils.VaccineUtils;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.BooleanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.boman.common.core.utils.StringUtils.isNotEmpty;
import static com.boman.common.core.utils.obj.ObjectUtils.isEmpty;
import static com.boman.common.core.utils.obj.ObjectUtils.map;
import static com.boman.common.redis.RedisKey.STS_CZRK_;

/**
 * 疫苗信息Service业务层处理
 *
 * @author ruoyi
 * @date 2021-09-05
 */
@Service
public class VaccineInfoServiceImpl implements IVaccineInfoService {

    private static final Logger LOGGER = LoggerFactory.getLogger(VaccineInfoServiceImpl.class);

    private static final String INSERT = "insert";
    private static final String EDIT = "edit";
    private static final String DELETE = "delete";
    private static JSONObject QIANSHANSHI = null, ZHEN = null, QIANSHANSHI_SINGEL = null;

    @Resource
    private VaccineInfoMapper vaccineInfoMapper;
    @Resource
    private VaccineInfoOperationMapper vaccineInfoOperationMapper;
    @Resource
    private VaccineInfoUserMapper vaccineInfoUserMapper;
    @Resource
    private RemoteDictDataService remoteDictDataService;
    @Resource
    private RemoteDeptService remoteDeptService;
    @Resource
    private IBaseSaveService saveService;
    @Resource
    private StandardlyMapper standardlyMapper;
    @Resource
    private RedisService redisService;

    /**
     * 查询疫苗信息
     *
     * @param id 疫苗信息ID
     * @return 疫苗信息
     */
    @Override
    public VaccineInfoOperation selectVaccineInfoById(Long id) {
        VaccineInfoOperation vaccineInfoOperation = vaccineInfoMapper.selectVaccineInfoById(id);
        if (vaccineInfoOperation != null) {
            String vaccineName = vaccineInfoOperation.getVaccineName();
            if (StringUtils.isNotBlank(vaccineName)) {
                String dictValue = vaccineInfoMapper.selectSysDictDataByDictLabel(vaccineName);
                vaccineInfoOperation.setDictValue(dictValue);
            }
/*            //重点行业
            String keyIndustries = vaccineInfoOperation.getKeyIndustries();
            //进行字典转换
            if (StringUtils.isNotBlank(keyIndustries)) {
                String keyTrades = changeDictData("key_trades", keyIndustries);
                vaccineInfoOperation.setKeyIndustries(keyTrades);
            }
            String other = vaccineInfoOperation.getOther();
            //进行字典转换
            if (StringUtils.isNotBlank(other)) {
                String otherStatus = changeDictData("other_status", other);
                vaccineInfoOperation.setKeyIndustries(otherStatus);
            }*/
        }
        return vaccineInfoOperation;
    }

    /**
     * 查询疫苗信息列表
     *
     * @param vaccineInfoOperation 疫苗信息
     * @return 疫苗信息
     */
    @Override
    public List<VaccineInfoOperation> selectVaccineInfoList(VaccineInfoOperation vaccineInfoOperation) {
        Long deptId = vaccineInfoOperation.getDeptId();
        if (deptId == null) {
            deptId = AuthUtils.getLoginUser().getSysUser().getDeptId();
            //判断是否是管理员
            List<SysRole> roles = AuthUtils.getLoginUser().getSysUser().getRoles();
            if (roles.size() > 0) {
                for (SysRole role : roles) {
                    String roleKey = role.getRoleKey();
                    if ("admin".equals(roleKey) || "city".equals(roleKey)) {
                        deptId = null;
                    }
                }
            }
        }
        Map<String, Object> params = vaccineInfoOperation.getParams();
        if (params != null) {
            Object age = params.get("age");
            if (age != null) {
                if (StringUtils.isNotBlank(age.toString())) {
                    String[] split = age.toString().split("-");
                    params.put("startAge", split[0]);
                    if (split.length == 2) {
                        params.put("endAge", split[1]);
                    }
                }
            }
        }
        //接种地点
        String vaccinationPlace = vaccineInfoOperation.getVaccinationPlace();
        List<String> idCardS = new ArrayList<>();
        boolean flag = true;
        if (StringUtils.isNotBlank(vaccinationPlace)) {
            VaccineInfoUser vaccineInfoUser = new VaccineInfoUser();
            vaccineInfoUser.setVaccinationPlace(vaccinationPlace);
            idCardS = vaccineInfoUserMapper.selectIdCardList(vaccineInfoUser);
            if (idCardS.size() == 0) {
                flag = false;
            }
            vaccineInfoOperation.setIdCardS(idCardS);
        }

        //如果查询条件查询疫苗表且没数据,就不要查询主表
        List<VaccineInfoOperation> vaccineInfoOperations = new ArrayList<>();
        if (flag) {
            //setAddrCondition(vaccineInfoOperation);
            //设置分页
            PageDomain pageDomain = TableSupport.buildPageRequest();
            Integer pageNum = pageDomain.getPageNum();
            Integer pageSize = pageDomain.getPageSize();
            if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
                String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
                PageHelper.startPage(pageNum, pageSize, orderBy);
            }

            if (deptId != null) {
                List<SysDept> sysDepts = remoteDeptService.listChildrenDepts(deptId);
                List<Long> deptIdList = new ArrayList<>();
                if (sysDepts != null && sysDepts.size() > 0) {
                    for (SysDept sysDept : sysDepts) {
                        Long id = sysDept.getId();
                        deptIdList.add(id);
                    }
                }
                vaccineInfoOperation.setDeptIdList(deptIdList);
            }
            LOGGER.info("查询开始");
            vaccineInfoOperations = vaccineInfoMapper.selectVaccineInfoList(vaccineInfoOperation);
            LOGGER.info("查询结束");
        }
        if (vaccineInfoOperations != null && vaccineInfoOperations.size() > 0) {
            for (VaccineInfoOperation infoOperation : vaccineInfoOperations) {
                //省
                String province = infoOperation.getProvince();
                //市
                String city = infoOperation.getCity();
                //区
                String region = infoOperation.getRegion();
/*                //乡镇
                String villageTowns = infoOperation.getVillageTowns();
                //村居
                String village = infoOperation.getVillage();
                //村民组（社区）
                String villagerGroup = infoOperation.getVillagerGroup();*/
                //户籍地
                String domicile = infoOperation.getDomicile();
                StringBuilder sbDomicile = new StringBuilder();
                StringBuilder sbNowIn = new StringBuilder();
                if (StringUtils.isNotBlank(province)) {
                    sbDomicile.append(province);
                    sbNowIn.append(province);
                }
                if (StringUtils.isNotBlank(city)) {
                    sbDomicile.append(city);
                    sbNowIn.append(city);
                }
                if (StringUtils.isNotBlank(region)) {
                    sbDomicile.append(region);
                    sbNowIn.append(region);
                }
                if (StringUtils.isNotBlank(domicile)) {
                    sbDomicile.append(domicile);
                }
                infoOperation.setDomicileSelect(sbDomicile.toString());
                //现居地
                String nowIn = infoOperation.getNowIn();
                if (StringUtils.isNotBlank(nowIn)) {
                    sbNowIn.append(nowIn);
                }
                infoOperation.setNowInSelect(sbNowIn.toString());
                String progress = infoOperation.getProgress();
                if (StringUtils.isBlank(progress) || "否".equals(progress)) {
                    //最后一次的接种时间
                    Date vaccinationTimeLast = infoOperation.getVaccinationTime();
                    //接种的疫苗名称
                    String vaccineNameLast = infoOperation.getVaccineName();
                    if (StringUtils.isNotBlank(vaccineNameLast)) {
                        Date date = vaccinationTimeNext(vaccinationTimeLast, vaccineNameLast);
                        infoOperation.setVaccinationTimeNext(date);
                    }
                }
/*                //重点行业
                String keyIndustries = infoOperation.getKeyIndustries();
                //进行字典转换
                if (StringUtils.isNotBlank(keyIndustries)) {
                    String keyTrades = changeDictData("key_trades", keyIndustries);
                    infoOperation.setKeyIndustries(keyTrades);
                }
                String other = infoOperation.getOther();
                //进行字典转换
                if (StringUtils.isNotBlank(other)) {
                    String otherStatus = changeDictData("other_status", other);
                    infoOperation.setKeyIndustries(otherStatus);
                }*/
            }
        }
        return vaccineInfoOperations;
    }

    //转换字典值
    private String changeDictData(String dictType, String dictValue) {
        return remoteDictDataService.selectDictLabel(dictType, dictValue);
    }

    /**
     * 放查询地址
     *
     * @param vaccineInfoOperation
     */
    private void setAddrCondition(VaccineInfoOperation vaccineInfoOperation) {
        // 当前登陆人所在部门，有可能是县，有可能是镇，有可能是村
        Long deptId = AuthUtils.getLoginUser().getSysUser().getDeptId();
        SysDept dept = remoteDeptService.getById(deptId);
        String deptName = dept.getDeptName();
        vaccineInfoOperation.setVillageTowns(deptName);
    }

    //下一针接种 时间
    public static Date vaccinationTimeNext(Date vaccinationTime, String vaccineNameLast) {
        Date date = new Date();
        if ("北京科兴中维".equals(vaccineNameLast)) {
            date = DateUtils.addDayOfDate(vaccinationTime, 14);
        } else if ("北京生物".equals(vaccineNameLast)) {
            date = DateUtils.addDayOfDate(vaccinationTime, 21);
        } else if ("深圳康泰".equals(vaccineNameLast)) {
            date = DateUtils.addDayOfDate(vaccinationTime, 28);
        } else if ("安徽智飞".equals(vaccineNameLast)) {
            date = DateUtils.addDayOfDate(vaccinationTime, 28);
        } else if ("兰州生物".equals(vaccineNameLast)) {
            date = DateUtils.addDayOfDate(vaccinationTime, 21);
        } else if ("成都生物".equals(vaccineNameLast)) {
            date = DateUtils.addDayOfDate(vaccinationTime, 21);
        } else if ("科兴大连".equals(vaccineNameLast)) {
            date = DateUtils.addDayOfDate(vaccinationTime, 21);
        } else if ("长春生物".equals(vaccineNameLast)) {
            date = DateUtils.addDayOfDate(vaccinationTime, 14);
        } else {
            date = vaccinationTime;
        }
        return date;
    }

    /**
     * 新增疫苗信息
     *
     * @param vaccineInfoOperation 疫苗信息
     * @return 结果
     */
    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
    public AjaxResult insertVaccineInfo(VaccineInfoOperation vaccineInfoOperation) {
        //获取身份证
        String idCard = vaccineInfoOperation.getIdCard();
        //先去查询该身份证信息 是否存在
        VaccineInfoOperation vaccineInfoOperationOld = vaccineInfoMapper.selectVaccineInfoByIdCard(idCard);
        if (vaccineInfoOperationOld == null || vaccineInfoOperationOld.getId() == null) {
            // 疫苗信息
//        genNowIn(vaccineInfoOperation);
            Long deptId = getDeptId(vaccineInfoOperation);
            vaccineInfoOperation.setDeptId(deptId);
            vaccineInfoOperation.setCreateTime(DateUtils.getNowDate());
            //提取出用户接种疫苗信息列表
            List<VaccineInfoUser> vaccineInfoUserList = vaccineInfoOperation.getVaccineInfoUserList();
            //最后一次接种时间
            Date vaccinationTime = null;
            String vaccineName = "";
            String jiCi = "";
            String isVaccination = vaccineInfoOperation.getIsVaccination();
            if (!"否".equals(isVaccination)) {
                if (vaccineInfoUserList != null && vaccineInfoUserList.size() > 0) {
                    for (VaccineInfoUser vaccineInfoUser : vaccineInfoUserList) {
                        if (StringUtils.isNotBlank(vaccineInfoUser.getVaccineName()) || vaccineInfoUser.getVaccinationTime() != null || StringUtils.isNotBlank(vaccineInfoUser.getVaccinationPlace()) || StringUtils.isNotBlank(vaccineInfoUser.getJici()) || StringUtils.isNotBlank(vaccineInfoUser.getProgress())) {
                            if (vaccinationTime == null) {
                                vaccinationTime = vaccineInfoUser.getVaccinationTime();
                            } else if (vaccineInfoUser.getVaccinationTime() != null && vaccineInfoUser.getVaccinationTime().compareTo(vaccinationTime) > 0) {
                                vaccinationTime = vaccineInfoUser.getVaccinationTime();
                            }
                            //剂次可能是 "加强针"
                            String jici = vaccineInfoUser.getJici();
                            if (StringUtils.isBlank(jiCi)) {
                                jiCi = vaccineInfoUser.getJici();
                            }
                            if (StringUtils.isBlank(vaccineName)) {
                                vaccineName = vaccineInfoUser.getVaccineName();
                            }
                            if (isNumeric(jici) && isNumeric(jiCi)) {
                                if (Integer.parseInt(jici) > Integer.parseInt(jiCi)) {
                                    jiCi = vaccineInfoUser.getJici();
                                    vaccineName = vaccineInfoUser.getVaccineName();
                                }
                            } else if (!isNumeric(jici)) {
                                jiCi = vaccineInfoUser.getJici();
                                vaccineName = vaccineInfoUser.getVaccineName();
                            }
                            vaccineInfoUser.setIdCard(vaccineInfoOperation.getIdCard());
                            vaccineInfoUser.setCreateBy(SecurityUtils.getUsername());
                            vaccineInfoUserMapper.insertVaccineInfoUser(vaccineInfoUser);
                        }
                    }
                }
            }
            //是否完成
            String isSuccess = getIsSuccess(vaccineName, jiCi);
            vaccineInfoOperation.setVaccinationTime(vaccinationTime);
            vaccineInfoOperation.setVaccineName(vaccineName);
            vaccineInfoOperation.setJici(jiCi);
            vaccineInfoOperation.setProgress(isSuccess);
            //只针对第一针
            //应种未种：死亡（包含里面的选项）-禁忌症（包含里面的选项）-已经接种的-缓种-其他,只针对第一针
            //应续未续：只打了一针（总共2针），智飞打了一次和二次都是应续未续,只要一样禁忌症和暂缓就都不算
            VaccineInfoOperation vaccineInfoOperationNew = shouldSlow(vaccineInfoOperation);


            int rows = vaccineInfoMapper.insertVaccineInfo(vaccineInfoOperationNew);

            // 疫苗信息新增操作记录
            vaccineInfoOperationNew.setOperationType(INSERT);
            vaccineInfoOperationNew.setVaccineInfoId(vaccineInfoOperation.getId());
            vaccineInfoOperationNew.setCreateBy(SecurityUtils.getUsername());
            vaccineInfoOperationNew.setVaccinationTime(vaccinationTime);
            vaccineInfoOperationNew.setVaccineName(vaccineName);
            vaccineInfoOperationMapper.insertVaccineInfoOperation(vaccineInfoOperationNew);
            return rows > 0 ? AjaxResult.success() : AjaxResult.error();
        } else {
            return AjaxResult.error("该用户信息已存在,请勿重复添加");
        }
    }

    //查询修改的时候,匹配出人员的部门
    private Long getDeptId(VaccineInfoOperation vaccineInfoOperation) {
        //乡镇
        String villageTowns = vaccineInfoOperation.getVillageTowns();
        List<SysDept> sysDepts = remoteDeptService.selectByDeptName(villageTowns);
        //村居
        String village = vaccineInfoOperation.getVillage();
        //村民组（社区）
        String villagerGroup = vaccineInfoOperation.getVillagerGroup();
        Long deptId = 1L;
        if (sysDepts != null && sysDepts.size() > 0) {
            if (StringUtils.isNotBlank(village)) {
                for (SysDept sysDept : sysDepts) {
                    String deptName = sysDept.getDeptName();
                    if (village.equals(deptName)) {
                        if (StringUtils.isNotBlank(villagerGroup)) {
                            for (SysDept child : sysDepts) {
                                String deptNameChild = child.getDeptName();
                                if (villagerGroup.equals(deptNameChild)) {
                                    deptId = child.getId();
                                    return deptId;
                                }
                            }

                        } else {
                            deptId = sysDept.getId();
                        }
                    }
                }
            } else {
                for (SysDept sysDept : sysDepts) {
                    if (villageTowns.equals(sysDept.getDeptName())) {
                        deptId = sysDept.getId();
                    }
                }
            }
        }
        return deptId;
    }


    /**
     * 判断是否完成
     *
     * @param vaccineName
     * @param jici
     * @return
     */
    public static String getIsSuccess(String vaccineName, String jici) {
        if ("北京科兴中维".equals(vaccineName)) {
            if ("2".equals(jici)) {
                return "是";
            } else {
                return "否";
            }
        } else if ("北京生物".equals(vaccineName)) {
            if ("2".equals(jici)) {
                return "是";
            } else {
                return "否";
            }
        } else if ("兰州生物".equals(vaccineName)) {
            if ("2".equals(jici)) {
                return "是";
            } else {
                return "否";
            }
        } else if ("深圳康泰".equals(vaccineName)) {
            if ("2".equals(jici)) {
                return "是";
            } else {
                return "否";
            }
        } else if ("安徽智飞".equals(vaccineName)) {
            if ("3".equals(jici)) {
                return "是";
            } else {
                return "否";
            }
        } else if ("成都生物".equals(vaccineName)) {
            if ("2".equals(jici)) {
                return "是";
            } else {
                return "否";
            }
        } else if ("科兴大连".equals(vaccineName)) {
            if ("2".equals(jici)) {
                return "是";
            } else {
                return "否";
            }
        } else if ("长春生物".equals(vaccineName)) {
            if ("2".equals(jici)) {
                return "是";
            } else {
                return "否";
            }
        } else if ("康希诺生物".equals(vaccineName)) {
            if ("1".equals(jici)) {
                return "是";
            }
        }

        return "否";
    }

    /**
     * 判断用户应种未种:就是没有有禁忌症或者暂缓接种的,应续未续
     *
     * @param vaccineInfoOperation
     * @return
     */
    public static VaccineInfoOperation shouldSlow(VaccineInfoOperation vaccineInfoOperation) {
        List<VaccineInfoUser> vaccineInfoUserList = vaccineInfoOperation.getVaccineInfoUserList();
        //默认是
        vaccineInfoOperation.setShouldBe("是");

        String contraindication = vaccineInfoOperation.getContraindication();
        //暂缓接种
        String suspend = vaccineInfoOperation.getSuspend();
        //其他:死亡,失踪失联
        String other = vaccineInfoOperation.getOther();
        //判断应种未种
        if (vaccineInfoUserList == null || vaccineInfoUserList.size() == 0) {
            //只判断第一针,就是一针没打
            //判断是否填写了禁忌症
            if (StringUtils.isNotBlank(contraindication) || StringUtils.isNotBlank(suspend) || StringUtils.isNotBlank(other)) {
                vaccineInfoOperation.setShouldBe("否");
                //有禁忌症,暂缓接种,其他:死亡,失踪失联就是否
                vaccineInfoOperation.setShouldSlow("否");
            }
        } else {
            //判断应续未续,只要是未完成说明可能是一针没打,可能是没打完,有禁忌症,暂缓接种,其他:死亡,失踪失联就是否
            //如果他打过针
            if (StringUtils.isNotBlank(contraindication) || StringUtils.isNotBlank(suspend) || StringUtils.isNotBlank(other)) {
                //有禁忌症,暂缓接种,其他:死亡,失踪失联就是否
                vaccineInfoOperation.setShouldSlow("否");
            } else {
                //没有异常情况,判断是否完成
                String progress = vaccineInfoOperation.getProgress();
                vaccineInfoOperation.setShouldSlow("否");
                if ("否".equals(progress)) {
                    vaccineInfoOperation.setShouldSlow("是");
                }
            }
        }
        return vaccineInfoOperation;
    }

    /**
     * 利用正则表达式判断字符串是否是数字
     *
     * @param str
     * @return
     */
    public static boolean isNumeric(String str) {
        if (StringUtils.isEmpty(str)) {
            return false;
        }
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    /**
     * 修改疫苗信息
     *
     * @param vaccineInfo 疫苗信息
     * @return 结果
     */
    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
    public AjaxResult updateVaccineInfo(VaccineInfoOperation vaccineInfo) {
        // 根据身份证查询数据
        VaccineInfoOperation oldInfo = vaccineInfoMapper.selectVaccineInfoByIdCard(vaccineInfo.getIdCard());
        boolean neetUpdate = false;
        if (oldInfo != null) {
            // 如果数据不等，即添加了一个别人的已存在身份证
            if (!oldInfo.getId().equals(vaccineInfo.getId())) {
                return AjaxResult.error("此身份证号非本人，请确认后再次输入！");
            }
        } else {
            neetUpdate = true;
        }
        Long deptId = getDeptId(vaccineInfo);
        vaccineInfo.setDeptId(deptId);

        vaccineInfo.setUpdateTime(DateUtils.getNowDate());
//        genNowIn(vaccineInfo);
        List<VaccineInfoUser> vaccineInfoUserList = vaccineInfo.getVaccineInfoUserList();
        //最后接种时间
        Date vaccinationTime = vaccineInfo.getVaccinationTime();
        //疫苗名称
        String vaccineName = "";
        //剂次
        String jiCi = vaccineInfo.getJici();
        String isVaccination = vaccineInfo.getIsVaccination();
        if (!"否".equals(isVaccination)) {
            if (vaccineInfoUserList != null && vaccineInfoUserList.size() > 0) {
                for (VaccineInfoUser vaccineInfoUser : vaccineInfoUserList) {
                    if (vaccineInfoUser.getId() != null) {
                        vaccineInfoUser.setUpdateBy(SecurityUtils.getUsername());

                        if (StringUtils.isNotBlank(vaccineInfoUser.getVaccineName()) || vaccineInfoUser.getVaccinationTime() != null || StringUtils.isNotBlank(vaccineInfoUser.getVaccinationPlace()) || StringUtils.isNotBlank(vaccineInfoUser.getJici()) || StringUtils.isNotBlank(vaccineInfoUser.getProgress())) {
                            if (vaccinationTime == null) {
                                vaccinationTime = vaccineInfoUser.getVaccinationTime();
                            } else if (vaccineInfoUser.getVaccinationTime() != null && vaccineInfoUser.getVaccinationTime().compareTo(vaccinationTime) > 0) {
                                vaccinationTime = vaccineInfoUser.getVaccinationTime();
                            }
                            //剂次可能是 "加强针"
                            String jici = vaccineInfoUser.getJici();
                            if (StringUtils.isBlank(jiCi)) {
                                jiCi = vaccineInfoUser.getJici();
                            }
                            if (StringUtils.isBlank(vaccineName)) {
                                vaccineName = vaccineInfoUser.getVaccineName();
                            }
                            if (isNumeric(jici) && isNumeric(jiCi)) {
                                if (Integer.parseInt(jici) > Integer.parseInt(jiCi)) {
                                    jiCi = vaccineInfoUser.getJici();
                                    vaccineName = vaccineInfoUser.getVaccineName();
                                }
                            } else if (!isNumeric(jici)) {
                                jiCi = vaccineInfoUser.getJici();
                                vaccineName = vaccineInfoUser.getVaccineName();
                            }
                            if (neetUpdate) {
                                vaccineInfoUser.setIdCard(vaccineInfo.getIdCard());
                            }
                            vaccineInfoUserMapper.updateVaccineInfoUser(vaccineInfoUser);
                        }

                    } else {
                        if (StringUtils.isNotBlank(vaccineInfoUser.getVaccineName()) || vaccineInfoUser.getVaccinationTime() != null || StringUtils.isNotBlank(vaccineInfoUser.getVaccinationPlace()) || StringUtils.isNotBlank(vaccineInfoUser.getJici()) || StringUtils.isNotBlank(vaccineInfoUser.getProgress())) {
                            //判断接种时间是否是新
                            if (vaccinationTime == null) {
                                vaccinationTime = vaccineInfoUser.getVaccinationTime();
                            } else if (vaccineInfoUser.getVaccinationTime() != null && vaccineInfoUser.getVaccinationTime().compareTo(vaccinationTime) > 0) {
                                vaccinationTime = vaccineInfoUser.getVaccinationTime();
                            }
                            //剂次可能是 "加强针"
                            String jici = vaccineInfoUser.getJici();
                            if (StringUtils.isBlank(jiCi)) {
                                jiCi = vaccineInfoUser.getJici();
                            }
                            if (StringUtils.isBlank(vaccineName)) {
                                vaccineName = vaccineInfoUser.getVaccineName();
                            }
                            if (isNumeric(jici) && isNumeric(jiCi)) {
                                if (Integer.parseInt(jici) > Integer.parseInt(jiCi)) {
                                    jiCi = vaccineInfoUser.getJici();
                                    vaccineName = vaccineInfoUser.getVaccineName();
                                }
                            } else if (!isNumeric(jici)) {
                                jiCi = vaccineInfoUser.getJici();
                                vaccineName = vaccineInfoUser.getVaccineName();
                            }
                            vaccineInfoUser.setIdCard(vaccineInfo.getIdCard());
                            vaccineInfoUser.setCreateBy(SecurityUtils.getUsername());
                            vaccineInfoUserMapper.insertVaccineInfoUser(vaccineInfoUser);
                        }
                    }
                }
            }
        }
        //是否完成
        String isSuccess = getIsSuccess(vaccineName, jiCi);
        //判断用户应种未种,应续未续
        vaccineInfo.setVaccineName(vaccineName);
        vaccineInfo.setVaccinationTime(vaccinationTime);
        vaccineInfo.setJici(jiCi);
        vaccineInfo.setProgress(isSuccess);
        VaccineInfoOperation vaccineInfoOperationNew = shouldSlow(vaccineInfo);

        int info = vaccineInfoMapper.updateVaccineInfo(vaccineInfoOperationNew);
        // 疫苗信息新增操作记录
        vaccineInfoOperationNew.setOperationType(EDIT);
        vaccineInfoOperationNew.setCreateTime(new Date());
        vaccineInfoOperationNew.setCreateBy(SecurityUtils.getUsername());
        vaccineInfoOperationNew.setVaccineInfoId(vaccineInfo.getId());
        vaccineInfoOperationMapper.insertVaccineInfoOperation(vaccineInfoOperationNew);
        return info > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 批量删除疫苗信息
     *
     * @param ids 需要删除的疫苗信息ID
     * @return 结果
     */
    @Override
    public int deleteVaccineInfoByIds(Long[] ids) {
        List<VaccineInfoOperation> vaccineInfos = vaccineInfoMapper.selectVaccineInfoByIds(ids);
        String userName = SecurityUtils.getUsername();
        for (VaccineInfoOperation vaccineInfoOperation : vaccineInfos) {
            // 疫苗信息新增操作记录
            vaccineInfoOperation.setOperationType(DELETE);
            vaccineInfoOperation.setCreateTime(new Date());
            vaccineInfoOperation.setCreateBy(userName);
            vaccineInfoOperation.setVaccineInfoId(vaccineInfoOperation.getId());
            vaccineInfoOperationMapper.insertVaccineInfoOperation(vaccineInfoOperation);
        }

        return vaccineInfoMapper.deleteVaccineInfoByIds(ids);
    }

    /**
     * 删除疫苗信息信息
     *
     * @param id 疫苗信息ID
     * @return 结果
     */
    @Override
    public int deleteVaccineInfoById(Long id) {
        VaccineInfoOperation vaccineInfo = vaccineInfoMapper.selectVaccineInfoById(id);
        vaccineInfo.setVaccineInfoId(id);
        vaccineInfo.setCreateBy(SecurityUtils.getUsername());
        vaccineInfo.setCreateTime(new Date());
        vaccineInfo.setOperationType(DELETE);
        return vaccineInfoMapper.deleteVaccineInfoById(id);
    }

    /**
     * 根据身份证号查询用户信息
     *
     * @param vaccineInfo
     * @return
     */
    @Override
    public VaccineInfoOperation findHjInfo(VaccineInfoOperation vaccineInfo) {
        VaccineInfoOperation hjInfo = vaccineInfoMapper.findHjInfo(vaccineInfo);
        if (hjInfo == null) {
            String idCard = vaccineInfo.getIdCard();
            if (StringUtils.isNotBlank(idCard)) {
                //根据身份证提取出生日和性别,年龄
                String sex = getSex(idCard);
                Integer age = getAge(idCard);
                String birthday = getBirthday(idCard);
                vaccineInfo.setAge(age);
                vaccineInfo.setGender(sex);
                vaccineInfo.setBirthday(birthday);
                return vaccineInfo;
            }
        }
        return hjInfo;
    }


    /**
     * 15位身份证号
     */
    private static final Integer FIFTEEN_ID_CARD = 15;
    /**
     * 18位身份证号
     */
    private static final Integer EIGHTEEN_ID_CARD = 18;
    private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

    /**
     * 根据身份证号获取性别
     *
     * @param IDCard
     * @return
     */
    public static String getSex(String IDCard) {
        String sex = "";
        if (StringUtils.isNotBlank(IDCard)) {
            //15位身份证号
            if (IDCard.length() == FIFTEEN_ID_CARD) {
                if (Integer.parseInt(IDCard.substring(14, 15)) % 2 == 0) {
                    sex = "女";
                } else {
                    sex = "男";
                }
                //18位身份证号
            } else if (IDCard.length() == EIGHTEEN_ID_CARD) {
                // 判断性别
                if (Integer.parseInt(IDCard.substring(16).substring(0, 1)) % 2 == 0) {
                    sex = "女";
                } else {
                    sex = "男";
                }
            }
        }
        return sex;
    }


    /**
     * 根据身份证号获取年龄
     *
     * @param IDCard
     * @return
     */
    public static Integer getAge(String IDCard) {
        Integer age = 0;
        Date date = new Date();
        if (StringUtils.isNotBlank(IDCard) && isValid(IDCard)) {
            //15位身份证号
            if (IDCard.length() == FIFTEEN_ID_CARD) {
                // 身份证上的年份(15位身份证为1980年前的)
                String uyear = "19" + IDCard.substring(6, 8);
                // 身份证上的月份
                String uyue = IDCard.substring(8, 10);
                // 当前年份
                String fyear = format.format(date).substring(0, 4);
                // 当前月份
                String fyue = format.format(date).substring(5, 7);
                if (Integer.parseInt(uyue) <= Integer.parseInt(fyue)) {
                    age = Integer.parseInt(fyear) - Integer.parseInt(uyear) + 1;
                    // 当前用户还没过生
                } else {
                    age = Integer.parseInt(fyear) - Integer.parseInt(uyear);
                }
                //18位身份证号
            } else if (IDCard.length() == EIGHTEEN_ID_CARD) {
                // 身份证上的年份
                String year = IDCard.substring(6).substring(0, 4);
                // 身份证上的月份
                String yue = IDCard.substring(10).substring(0, 2);
                // 当前年份
                String fyear = format.format(date).substring(0, 4);
                // 当前月份
                String fyue = format.format(date).substring(5, 7);
                // 当前月份大于用户出身的月份表示已过生日
                if (Integer.parseInt(yue) <= Integer.parseInt(fyue)) {
                    age = Integer.parseInt(fyear) - Integer.parseInt(year) + 1;
                    // 当前用户还没过生日
                } else {
                    age = Integer.parseInt(fyear) - Integer.parseInt(year);
                }
            }
        }

        return age;
    }


    /**
     * 身份证验证
     *
     * @param id 号码内容
     * @return 是否有效
     */
    public static boolean isValid(String id) {
        Boolean validResult = true;
        //校验长度只能为15或18
        int len = id.length();
        if (len != FIFTEEN_ID_CARD && len != EIGHTEEN_ID_CARD) {
            validResult = false;
        }
        //校验生日
        if (!validDate(id)) {
            validResult = false;
        }
        return validResult;
    }

    /**
     * 校验生日
     *
     * @param id
     * @return
     */
    private static boolean validDate(String id) {
        try {
            String birth = id.length() == 15 ? "19" + id.substring(6, 12) : id.substring(6, 14);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            Date birthDate = sdf.parse(birth);
            if (!birth.equals(sdf.format(birthDate))) {
                return false;
            }
        } catch (ParseException e) {
            return false;
        }
        return true;
    }

    /**
     * 获取出生日期  yyyy年MM月dd日
     *
     * @param IDCard
     * @return
     */
    public static String getBirthday(String IDCard) {
        String birthday = "";
        String year = "";
        String month = "";
        String day = "";
        if (StringUtils.isNotBlank(IDCard)) {
            //15位身份证号
            if (IDCard.length() == FIFTEEN_ID_CARD) {
                // 身份证上的年份(15位身份证为1980年前的)
                year = "19" + IDCard.substring(6, 8);
                //身份证上的月份
                month = IDCard.substring(8, 10);
                //身份证上的日期
                day = IDCard.substring(10, 12);
                //18位身份证号
            } else if (IDCard.length() == EIGHTEEN_ID_CARD) {
                // 身份证上的年份
                year = IDCard.substring(6).substring(0, 4);
                // 身份证上的月份
                month = IDCard.substring(10).substring(0, 2);
                //身份证上的日期
                day = IDCard.substring(12).substring(0, 2);
            }
            birthday = year + "-" + month + "-" + day;
        }
        return birthday;
    }

    private void genNowIn(VaccineInfoOperation vaccineInfo) {
        // 现居地
        String nowIn = vaccineInfo.getProvince() + vaccineInfo.getCity() + vaccineInfo.getRegion();
        nowIn += vaccineInfo.getNowIn();
        vaccineInfo.setNowIn(nowIn);

        // 户籍
        String domic = vaccineInfo.getVillageTowns() + vaccineInfo.getVillage() + vaccineInfo.getVillagerGroup() + vaccineInfo.getDomicile();
        vaccineInfo.setDomicile(domic);
    }

    /**
     * 功能描述: 统计
     *
     * @return java.util.List<com.alibaba.fastjson.JSONObject>
     */
    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
    public AjaxResult statistic() {
        List<SysDept> allTowns = remoteDeptService.getByParentId(1L);
        List<JSONObject> result = new ArrayList<>(allTowns.size());
        List<String> townNameList = map(allTowns, SysDept::getDeptName);

        LOGGER.info("开始查询");
        long l = System.currentTimeMillis();
        List<VaccineInfoOperation> infoList = vaccineInfoMapper.listByTotalTaskCnt();
        LOGGER.info("查询用时: {} s", (System.currentTimeMillis() - l) / 1000);
        // 暂且如此
        standardlyMapper.updateAll(SecurityUtils.getUsername());
        Date todayStart = DateUtils.getTodayStart(), todayEnd = DateUtils.getTodayEnd();
        for (String townName : townNameList) {
            int zrws = 0, zjzs = 0, drrws = 0, drjzs = 0, dez = 0, dsz = 0;
            JSONObject jsonObject = new JSONObject(10);
            jsonObject.put("xz", townName);
            for (VaccineInfoOperation info : infoList) {
                if (!townName.equals(info.getVillageTowns())) {
                    continue;
                }
                // 总任务数
                zrws++;


                // 总接种数
                if (isNotEmpty(info.getJici())) {
                    if ("加强针".equals(info.getJici())) {
                        zjzs++;
                    } else if (Integer.parseInt(info.getJici()) >= 1) {
                        zjzs++;
                    }
                }

                Date vaccinationTime = info.getVaccinationTime();
                if (null != vaccinationTime && vaccinationTime.after(todayStart) && vaccinationTime.before(todayEnd)) {
                    drjzs++;
                    if ("2".equals(info.getJici())) {
                        dez++;
                    } else if ("3".equals(info.getJici())) {
                        dsz++;
                    }
                }

                // 接种时间和接种疫苗种类判断 当日任务数
                if (null != vaccinationTime) {
                    String vaccineName = info.getVaccineName();
                    drrws = judgeTodayTask(vaccineName, vaccinationTime, drrws, todayStart, todayEnd);
                }
            }

            jsonObject.put("zrws", zrws);
            jsonObject.put("zjzs", zjzs);
            jsonObject.put("wcl1", NumberUtils.percent(zjzs, zrws));
            jsonObject.put("wwcs", zrws - zjzs);

            jsonObject.put("drjzs", drjzs);
            jsonObject.put("drrws", drrws);
            jsonObject.put("dez", dez);
            jsonObject.put("dsz", dsz);
            jsonObject.put("hj", dez + dsz);
            jsonObject.put("wcl2", NumberUtils.percent(dez + dsz, drjzs));
            LOGGER.info("疫苗接种统计数据为: {}", JSON.toJSONString(jsonObject));
            result.add(jsonObject);
            jsonObject.put("create_time", new Timestamp(System.currentTimeMillis()));
            jsonObject.put("update_time", new Timestamp(System.currentTimeMillis()));
            jsonObject.put("update_by", SecurityUtils.getUsername());
            Long maxId = IdUtils.getMaxId("vaccination_statistic", "id");
            jsonObject.put("id", maxId);
            saveService.insertRow("vaccination_statistic", jsonObject);
        }

        return AjaxResult.success("成功", result);
    }

    private int judgeTodayTask(String vaccineName, Date vaccinationTime, int drrws, Date todayStart, Date todayEnd) {
        Date nextTime = VaccineUtils.getNextTime(vaccineName, vaccinationTime);
        if (nextTime == null) {
            return drrws;
        }

        if (nextTime.before(todayEnd) && nextTime.after(todayStart)) {
            drrws++;
        }

        return drrws;
    }

    @Override
    public List<JSONObject> list() {
        String deptName = AuthUtils.getLoginUser().getSysUser().getDept().getDeptName();
        if ("潜山市".equals(deptName)) {
            return standardlyMapper.list();
        }

        return standardlyMapper.list1(deptName);
    }

    /**
     * 功能描述: 安康码根据身份证号码查询信息
     *
     * @param idCard idCard
     * @return com.alibaba.fastjson.JSONObject
     */
    @Override
    public JSONObject getByIdCard(String idCard) {
        VaccineInfoOperation info = vaccineInfoMapper.getByIdCard(idCard);
        JSONObject result = new JSONObject(2);
        if (info == null) {
            return result;
        }

        // 姓名
        result.put("userName", info.getUserName());
        // 家庭住址
        result.put("domicile", info.getDomicile());
        return result;
    }

    @Override
    public VaccineInfoOperation getById(Long id) {
        return vaccineInfoMapper.selectVaccineInfoById(id);
    }

    @Override
    public JSONObject stsByApplet(Long townId, Long villageId, String userName) {
        Long deptId = AuthUtils.getLoginUser().getSysUser().getDeptId();
        List<Long> deptIdList = new ArrayList<>(16);
        // 未加搜索条件
        if (isEmpty(townId) && isEmpty(villageId)) {
            List<SysRole> roles = AuthUtils.getLoginUser().getSysUser().getRoles();
            if (isNotEmpty(roles)) {
                for (SysRole role : roles) {
                    String roleKey = role.getRoleKey();
                    //判断是否是管理员
                    if ("admin".equals(roleKey) || "city".equals(roleKey)) {
                        deptId = null;
                        break;
                    }
                }
            }

            if (deptId != null) {
                List<SysDept> sysDepts = remoteDeptService.listChildrenDepts(deptId);
                if (sysDepts != null && sysDepts.size() > 0) {
                    for (SysDept sysDept : sysDepts) {
                        Long id = sysDept.getId();
                        deptIdList.add(id);
                    }
                }
            }
        } else {
            // 查村
            if (!isEmpty(townId) && !isEmpty(villageId)) {
                List<SysDept> sysDepts = remoteDeptService.listChildrenDepts(villageId);
                deptIdList = sysDepts.stream().map(SysDept::getId).collect(Collectors.toList());
            } else if (!isEmpty(townId) && isEmpty(villageId)) {
                // 查镇
                List<SysDept> sysDepts = remoteDeptService.listChildrenDepts(townId);
                deptIdList = sysDepts.stream().map(SysDept::getId).collect(Collectors.toList());
            }
        }

        int yrl = vaccineInfoMapper.stsByYrl(deptIdList, userName);
        int wrl = vaccineInfoMapper.stsByWrl(deptIdList, userName);
        JSONObject result = new JSONObject(3);
        result.put("yrl", yrl);
        result.put("wrl", wrl);
        result.put("total", wrl + yrl);
        return result;
    }

    /**
     * 功能描述: 当前单位：镇，村：7个，组：300个，常住人口：5000人，新增 2人  减少 2人
     *
     * @return com.alibaba.fastjson.JSONObject
     */
    @Override
    public JSONObject stsByCzrk() {
        JSONObject result = new JSONObject(16);
        SysUser sysUser = AuthUtils.getLoginUser().getSysUser();
        String deptName = sysUser.getDept().getDeptName();
        Long deptId = sysUser.getDeptId(); // 当前登陆人的deptId
        result.put("dqdw", deptName);  // 当前单位

        List<SysRole> roles = sysUser.getRoles();
        List<String> roleKeySets = map(roles, SysRole::getRoleKey);
        String todayStart = DateUtils.getTodayStartStr();
        String todayEnd = DateUtils.getTodayEndStr();
        VaccineInfoOperation condition = new VaccineInfoOperation();
        condition.setStartTime(todayStart);
        condition.setEndTime(todayEnd);
        condition.setRyrl(true);
        // 市领导
        if (roleKeySets.contains("city") || roleKeySets.contains("admin") || roleKeySets.contains("yanshi")) {
            JSONObject jsonObject = redisService.getCacheObject(packRedisKey("single:" + deptId));
            if (isNotEmpty(jsonObject)) {
                QIANSHANSHI_SINGEL = jsonObject;
                return jsonObject;
            }

            ThreadPoolService.execute(() -> {
                List<SysDept> allDepts = remoteDeptService.listChildrenDepts(1L);
                List<SysDept> townsDepts = new ArrayList<>(16);
                for (SysDept allDept : allDepts) {
                    if (isEmpty(allDept.getParentId())) continue;
                    if (allDept.getParentId() == (1L)) {
                        townsDepts.add(allDept);
                    }
                }
                result.put("zhen", townsDepts.size()); // 镇

                List<SysDept> cunDepts = new ArrayList<>(16);
                for (SysDept townsDept : townsDepts) {
                    for (SysDept allDept : allDepts) {
                        if (isEmpty(allDept.getParentId())) continue;
                        if (townsDept.getId().equals(allDept.getParentId())) {
                            cunDepts.add(allDept);
                        }
                    }
                }
                result.put("cun", isEmpty(cunDepts) ? 0 : cunDepts.size());

                List<SysDept> zuDept = new ArrayList<>(16);
                for (SysDept cunDept : cunDepts) {
                    for (SysDept allDept : allDepts) {
                        if (cunDept.getId().equals(allDept.getParentId())) {
                            zuDept.add(allDept);
                        }
                    }
                }

                result.put("zu", isEmpty(zuDept) ? 0 : zuDept.size()); // 组
                int czrk = vaccineInfoMapper.countCzrk(condition); // 常住人口
                result.put("czrk", czrk);

                int xz = vaccineInfoMapper.countByXz(condition); // 新增
                int js = vaccineInfoMapper.countByJs(condition);// 减少
                result.put("xz", xz);
                result.put("js", js);

                condition.setRyrl(null); // 查全部
                int zrs = vaccineInfoMapper.countCzrk(condition);
                String bfb = NumberUtils.percent(czrk, zrs);
                result.put("bfb", bfb);
                result.put("zrs", zrs);
                setIntoRedis(packRedisKey("single:" + deptId), result);
                QIANSHANSHI_SINGEL = result;
            });

            return QIANSHANSHI_SINGEL;
        } else if (roleKeySets.contains("sys:town")) {
            JSONObject jsonObject = redisService.getCacheObject(packRedisKey("town:" + deptId));
            if (isNotEmpty(jsonObject)) {
                return jsonObject;
            }

            townSts(result, condition, deptId, deptName, true);
//            redisService.setCacheObject(packRedisKey("town:" + deptId), result, 1L, TimeUnit.DAYS);
            setIntoRedis(packRedisKey("town:" + deptId), result);
        }

        return result;
    }

    /**
     * 功能描述: 项目首页统计信息，
     * 当前单位：镇，村：7个，组：300个，常住人口：5000人，新增 2人  减少 2人
     *
     * @return com.boman.domain.dto.AjaxResult
     */
    @Override
    public JSONObject stsByCzrkHomePage() {
        JSONObject result = new JSONObject(16);
        // 当前登陆人的deptId
        SysUser sysUser = AuthUtils.getLoginUser().getSysUser();
        String deptName = sysUser.getDept().getDeptName();
        result.put("dqdw", deptName); // 当前单位

        List<String> roleKeySets = map(sysUser.getRoles(), SysRole::getRoleKey);

        VaccineInfoOperation condition = new VaccineInfoOperation();
        condition.setStartTime(DateUtils.getTodayStartStr());
        condition.setEndTime(DateUtils.getTodayEndStr());
        condition.setRyrl(true);
        Long deptId = sysUser.getDeptId();

        // 市领导 todo 此处不应该写死
        if (roleKeySets.contains("city") || roleKeySets.contains("admin") || roleKeySets.contains("yanshi")) {
            JSONObject jsonObject = redisService.getCacheObject(packRedisKey(deptId + ""));
            if (isNotEmpty(jsonObject)) {
                QIANSHANSHI = jsonObject;
                return jsonObject;
            }

            ThreadPoolService.execute(()->{
                List<SysDept> allDepts = remoteDeptService.listChildrenDepts(1L);
                List<SysDept> townsDepts = new ArrayList<>(16);
                for (SysDept allDept : allDepts) {
                    if (isEmpty(allDept.getParentId())) continue;
                    if (allDept.getParentId() == (1L)) {
                        townsDepts.add(allDept);
                    }
                }
                result.put("zhen", townsDepts.size()); // 镇

                List<SysDept> cunDepts = new ArrayList<>(16);
                for (SysDept townsDept : townsDepts) {
                    for (SysDept allDept : allDepts) {
                        if (isEmpty(allDept.getParentId())) continue;
                        if (townsDept.getId().equals(allDept.getParentId())) {
                            cunDepts.add(allDept);
                        }
                    }
                }
                result.put("cun", isEmpty(cunDepts) ? 0 : cunDepts.size());

                List<SysDept> zuDept = new ArrayList<>(16);
                for (SysDept cunDept : cunDepts) {
                    for (SysDept allDept : allDepts) {
                        if (cunDept.getId().equals(allDept.getParentId())) {
                            zuDept.add(allDept);
                        }
                    }
                }

                result.put("zu", isEmpty(zuDept) ? 0 : zuDept.size()); // 组
                int czrk = vaccineInfoMapper.countCzrk(condition); // 常住人口
                result.put("czrk", czrk);

                int xz = vaccineInfoMapper.countByXz(condition); // 新增
                int js = vaccineInfoMapper.countByJs(condition);// 减少
                result.put("xz", xz);
                result.put("js", js);

                condition.setRyrl(null); // 查全部
                int zrs = vaccineInfoMapper.countCzrk(condition);
                String bfb = NumberUtils.percent(czrk, zrs);
                result.put("bfb", bfb);
                result.put("zrs", zrs);

                // 以各个镇为单位单独处理 townsDepts
                ArrayList<JSONObject> towsDataList = new ArrayList<>(20);
                for (SysDept townsDept : townsDepts) {
                    JSONObject townsResult = new JSONObject(16);
                    townSts(townsResult, condition, townsDept.getId(), townsDept.getDeptName(), false);
                    towsDataList.add(townsResult);
                }

                result.put("townDatas", towsDataList);
//                redisService.setCacheObject(packRedisKey(deptId + ""), result, 1L, TimeUnit.DAYS);
                setIntoRedis(packRedisKey(deptId + ""), result);
                QIANSHANSHI = result;
            });

            return QIANSHANSHI;
        } else if (roleKeySets.contains("sys:town")) {
            JSONObject jsonObject = redisService.getCacheObject(packRedisKey("town:" + deptId));
            if (isNotEmpty(jsonObject)) {
                ZHEN = jsonObject;
                return jsonObject;
            }

            ThreadPoolService.execute(() -> {
                townSts(result, condition, deptId, deptName, true);
//                redisService.setCacheObject(packRedisKey("town:" + deptId), result, 1L, TimeUnit.DAYS);
                setIntoRedis(packRedisKey("town:" + deptId), result);
            });

            return ZHEN;
        }

        return result;
    }

    private void townSts(JSONObject result, VaccineInfoOperation condition, Long deptId, String deptName, boolean percent) {
        // 乡镇以下的所有部门
        List<SysDept> depts = remoteDeptService.listChildrenDepts(deptId);
        List<SysDept> cunDepts = new ArrayList<>(16);
        for (SysDept dept : depts) {
            if (isEmpty(dept.getParentId())) continue;
            if (deptId.equals(dept.getParentId())) {
                cunDepts.add(dept);
            }
        }
        result.put("cun", isEmpty(cunDepts) ? 0 : cunDepts.size());

        List<SysDept> zuDept = new ArrayList<>(16);
        for (SysDept cunDept : cunDepts) {
            for (SysDept dept : depts) {
                if (cunDept.getId().equals(dept.getParentId())) {
                    zuDept.add(dept);
                }
            }
        }

        result.put("zu", isEmpty(zuDept) ? 0 : zuDept.size());
        condition.setDeptIdList(map(depts, SysDept::getId));
        int czrk = vaccineInfoMapper.countCzrk(condition);
        result.put("czrk", czrk);

        // 常住人口占总人口的百分比
        if (BooleanUtils.isTrue(percent)) {
            condition.setRyrl(null); // 查全部
            int zrs = vaccineInfoMapper.countCzrk(condition);
            String bfb = NumberUtils.percent(czrk, zrs);
            result.put("bfb", bfb);
        }

        int xz = vaccineInfoMapper.countByXz(condition);
        int js = vaccineInfoMapper.countByJs(condition);
        result.put("xz", xz);
        result.put("js", js);
        result.put("zhen", deptName);
    }

    @Override
    public int countByJs(VaccineInfoOperation condition) {
        SysUser sysUser = AuthUtils.getLoginUser().getSysUser();
        Long deptId = sysUser.getDeptId();
        List<SysRole> roles = sysUser.getRoles();
        List<String> roleKeySets = map(roles, SysRole::getRoleKey);
        String todayStart = DateUtils.getTodayStartStr();
        String todayEnd = DateUtils.getTodayEndStr();
        condition.setStartTime(todayStart);
        condition.setEndTime(todayEnd);
        if (roleKeySets.contains("sys:town")) {
            // 乡镇以下的所有部门
            List<SysDept> depts = remoteDeptService.listChildrenDepts(deptId);
            condition.setDeptIdList(map(depts, SysDept::getId));
        }

        return vaccineInfoMapper.countByJs(condition);
    }

    @Override
    public List<VaccineInfoOperation> listByJs(VaccineInfoOperation condition) {
        SysUser sysUser = AuthUtils.getLoginUser().getSysUser();
        Long deptId = sysUser.getDeptId();
        List<SysRole> roles = sysUser.getRoles();
        List<String> roleKeySets = map(roles, SysRole::getRoleKey);
        String todayStart = DateUtils.getTodayStartStr();
        String todayEnd = DateUtils.getTodayEndStr();
        condition.setStartTime(todayStart);
        condition.setEndTime(todayEnd);
        if (roleKeySets.contains("sys:town")) {
            // 乡镇以下的所有部门
            List<SysDept> depts = remoteDeptService.listChildrenDepts(deptId);
            condition.setDeptIdList(map(depts, SysDept::getId));
        }
        List<VaccineInfoOperation> infoOperations = vaccineInfoMapper.listByJs(condition);
        for (VaccineInfoOperation infoOperation : infoOperations) {
            String province = infoOperation.getProvince(); //省
            String city = infoOperation.getCity();  //市
            String region = infoOperation.getRegion();   //区
            String domicile = infoOperation.getDomicile(); //户籍地
            StringBuilder sbDomicile = new StringBuilder();
            StringBuilder sbNowIn = new StringBuilder();
            if (StringUtils.isNotBlank(province)) {
                sbDomicile.append(province);
                sbNowIn.append(province);
            }
            if (StringUtils.isNotBlank(city)) {
                sbDomicile.append(city);
                sbNowIn.append(city);
            }
            if (StringUtils.isNotBlank(region)) {
                sbDomicile.append(region);
                sbNowIn.append(region);
            }
            if (StringUtils.isNotBlank(domicile)) {
                sbDomicile.append(domicile);
            }

            String nowIn = infoOperation.getNowIn(); //现居地
            if (StringUtils.isNotBlank(nowIn)) {
                sbNowIn.append(nowIn);
            }

            infoOperation.setDomicileSelect(sbDomicile.toString());
            infoOperation.setNowInSelect(sbNowIn.toString());
        }
        return infoOperations;
    }

    @Override
    public int countByXz(VaccineInfoOperation condition) {
        SysUser sysUser = AuthUtils.getLoginUser().getSysUser();
        Long deptId = sysUser.getDeptId();
        List<SysRole> roles = sysUser.getRoles();
        List<String> roleKeySets = map(roles, SysRole::getRoleKey);
        String todayStart = DateUtils.getTodayStartStr();
        String todayEnd = DateUtils.getTodayEndStr();
        condition.setStartTime(todayStart);
        condition.setEndTime(todayEnd);
        if (roleKeySets.contains("sys:town")) {
            // 乡镇以下的所有部门
            List<SysDept> depts = remoteDeptService.listChildrenDepts(deptId);
            condition.setDeptIdList(map(depts, SysDept::getId));
        }

        return vaccineInfoMapper.countByXz(condition);
    }

    @Override
    public List<VaccineInfoOperation> listByXz(VaccineInfoOperation condition) {
        SysUser sysUser = AuthUtils.getLoginUser().getSysUser();
        Long deptId = sysUser.getDeptId();
        List<SysRole> roles = sysUser.getRoles();
        List<String> roleKeySets = map(roles, SysRole::getRoleKey);
        String todayStart = DateUtils.getTodayStartStr();
        String todayEnd = DateUtils.getTodayEndStr();
        condition.setStartTime(todayStart);
        condition.setEndTime(todayEnd);
        if (roleKeySets.contains("sys:town")) {
            // 乡镇以下的所有部门
            List<SysDept> depts = remoteDeptService.listChildrenDepts(deptId);
            condition.setDeptIdList(map(depts, SysDept::getId));
        }

        List<VaccineInfoOperation> infoOperations = vaccineInfoMapper.listByXz(condition);
        for (VaccineInfoOperation infoOperation : infoOperations) {
            String province = infoOperation.getProvince(); //省
            String city = infoOperation.getCity();  //市
            String region = infoOperation.getRegion();   //区
            String domicile = infoOperation.getDomicile(); //户籍地
            StringBuilder sbDomicile = new StringBuilder();
            StringBuilder sbNowIn = new StringBuilder();
            if (StringUtils.isNotBlank(province)) {
                sbDomicile.append(province);
                sbNowIn.append(province);
            }
            if (StringUtils.isNotBlank(city)) {
                sbDomicile.append(city);
                sbNowIn.append(city);
            }
            if (StringUtils.isNotBlank(region)) {
                sbDomicile.append(region);
                sbNowIn.append(region);
            }
            if (StringUtils.isNotBlank(domicile)) {
                sbDomicile.append(domicile);
            }

            String nowIn = infoOperation.getNowIn(); //现居地
            if (StringUtils.isNotBlank(nowIn)) {
                sbNowIn.append(nowIn);
            }

            infoOperation.setDomicileSelect(sbDomicile.toString());
            infoOperation.setNowInSelect(sbNowIn.toString());
        }

        return infoOperations;
    }

    @Override
    public AjaxResult deleteCzrk(VaccineInfoOperation vaccineInfoOperation) {
        VaccineInfoOperation operation = vaccineInfoMapper.selectVaccineInfoById(vaccineInfoOperation.getId());
        if (null == operation) {
            return AjaxResult.error("该信息不存在，无法删除");
        }

//        if (isEmpty(operation.getVillageTowns())) {
//            return AjaxResult.error("该人员为未认领人员，无法删除");
//        }

        vaccineInfoOperation.setUpdateBy(AuthUtils.getLoginUser().getSysUser().getUserName());
        int delete = vaccineInfoMapper.deleteCzrk(vaccineInfoOperation);
        return delete > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    @Override
    public List<VaccineInfoOperation> family(String code) {
        if (isEmpty(code)) {
            return Collections.emptyList();
        }

        List<VaccineInfoOperation> infoOperations = vaccineInfoMapper.listByCode(code);
        for (VaccineInfoOperation infoOperation : infoOperations) {
            String province = infoOperation.getProvince(); //省
            String city = infoOperation.getCity();  //市
            String region = infoOperation.getRegion();   //区
            String domicile = infoOperation.getDomicile(); //户籍地
            StringBuilder sbDomicile = new StringBuilder();
            StringBuilder sbNowIn = new StringBuilder();
            if (StringUtils.isNotBlank(province)) {
                sbDomicile.append(province);
                sbNowIn.append(province);
            }
            if (StringUtils.isNotBlank(city)) {
                sbDomicile.append(city);
                sbNowIn.append(city);
            }
            if (StringUtils.isNotBlank(region)) {
                sbDomicile.append(region);
                sbNowIn.append(region);
            }
            if (StringUtils.isNotBlank(domicile)) {
                sbDomicile.append(domicile);
            }

            String nowIn = infoOperation.getNowIn(); //现居地
            if (StringUtils.isNotBlank(nowIn)) {
                sbNowIn.append(nowIn);
            }

            infoOperation.setDomicileSelect(sbDomicile.toString());
            infoOperation.setNowInSelect(sbNowIn.toString());
        }

        return infoOperations;
    }

    /**
     * 功能描述: 回收站的还原功能
     *
     * @param id id
     * @return int
     */
    @Override
    public int reduction(String id) {
        if (isEmpty(id)) return 0;

        return vaccineInfoMapper.reduction(id);
    }

    private String packRedisKey(String deptId){
        return STS_CZRK_ + deptId + ":" + DateUtils.getDate();
    }

    private void setIntoRedis(String key, Object result){
        redisService.setCacheObject(key, result, 1L, TimeUnit.HOURS);
    }
}
