package com.boman.web.core.service;


import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.nacos.common.http.HttpUtils;
import com.boman.common.core.utils.DateUtils;
import com.boman.common.core.utils.StringUtils;
import com.boman.common.core.utils.number.NumberUtils;
import com.boman.common.core.utils.obj.ObjectUtils;
import com.boman.common.datasource.annotation.Master;
import com.boman.common.redis.service.RedisService;
import com.boman.common.security.service.TokenService;
import com.boman.domain.*;
import com.boman.domain.dto.AjaxResult;
import com.boman.domain.dto.FormDataDto;
import com.boman.system.api.RemoteDeptService;
import com.boman.system.api.RemoteUserService;
import com.boman.web.core.domain.AccountingData;
import com.boman.web.core.domain.BirthRecords;
import com.boman.web.core.domain.TSampling514;
import com.boman.web.core.domain.ToQianshanPersonner;
import com.boman.web.core.domain.vo.AccountingDataVo;
import com.boman.web.core.mapper.AccountingDataMapper;
import com.boman.web.core.mapper.CzrkMapper;
import com.boman.web.core.mapper.GridInfoMapper;
import com.boman.web.core.service.accounting.IAccountingDataService;
import com.boman.web.core.service.birth.BirthRecordsService;
import com.boman.web.core.service.common.ICommonService;
import com.boman.web.core.service.czrk.CzrkServiceImpl;
import com.boman.web.core.service.czrk.ICzrkJzdzService;
import com.boman.web.core.service.ip.IpTimesService;
import com.boman.web.core.service.toQianShan.ToQianshanPersonnerService;
import com.boman.web.core.utils.AuthUtils;
import com.boman.web.core.utils.HttpClientUtils;
import lombok.SneakyThrows;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;

import javax.annotation.Resource;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

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_;
import static com.boman.domain.constant.AttendanceConst.*;


/**
 * @author tjf
 * @Date: 2021/08/04/17:49
 */
@Component
public class TaskService {

    @Autowired
    private CzrkMapper czrkMapper;
    @Resource
    private RemoteDeptService remoteDeptService;
    @Resource
    private RedisService redisService;
    @Resource
    private ICzrkJzdzService czrkJzdzService;

    @Resource
    private TableServiceCmdService tableServiceCmdService;

    @Resource
    private RemoteUserService remoteUserService;

    @Resource
    private BirthRecordsService birthRecordsService;

    @Resource
    private ICommonService commonService;

    @Resource
    private IAccountingDataService accountingDataService;

    @Resource
    private ToQianshanPersonnerService toQianshanPersonnerService;

    @Resource
    private SqlSessionFactory sqlSessionFactory;
    private static final String tableName = "attendance_table";

    /**
     * 每月1号往考勤记录表根据用户插入当月的数据 每月一号00:00分
     */
    public void configureTasks() {
        //获取当月每一天
        String date = DateUtils.getDate();
        List<String> monthEveryDays = DateUtils.getMonthEveryDays(date);
        //获取所有用户
        List<SysUser> sysUsers = remoteUserService.selectUserListAll();
        if (sysUsers != null && sysUsers.size() > 0) {
            if (monthEveryDays != null) {
                JSONObject condition = new JSONObject();
                //需要ATTENDANCE_TABLE_TODAYTIME字段是查询可见
                condition.put(ATTENDANCE_TABLE_TODAYTIME, monthEveryDays);
                condition.put(IS_DEL, "N");
                //先去查询是否已经存在当前日期的记录
                List<JSONObject> byMap = commonService.getByMap(tableName, condition);
                if (byMap != null) {
                    List<String> days = new ArrayList<>();
                    for (JSONObject jsonObject : byMap) {
                        String day = jsonObject.get(ATTENDANCE_TABLE_TODAYTIME).toString();
                        days.add(day);
                    }
                    monthEveryDays.removeAll(days);
                }
                for (String monthEveryDay : monthEveryDays) {
                    for (SysUser sysUser : sysUsers) {
                        JSONObject commitData = new JSONObject();
                        commitData.put(ATTENDANCE_USER_NAME, sysUser.getUserName());
                        commitData.put(ATTENDANCE_USER_ID, sysUser.getId());
                        commitData.put(ATTENDANCE_DEPT_ID, sysUser.getDeptId());
                        commitData.put(ATTENDANCE_TABLE_TODAYTIME, monthEveryDay);
                        commitData.put(ATTENDANCE_TABLE_CREATE_TIME, DateUtils.getNowDate());
                        commitData.put(ATTENDANCE_TABLE_CREATE_BY, "admin");
                        FormDataDto dto = new FormDataDto();
                        dto.setObjId(-1L);
                        dto.setTable(tableName);
                        dto.setFixedData(commitData);
                        tableServiceCmdService.objectSave(dto);
                    }
                }
            }
        }
    }

    /***
     * 定时执行首页数据任务（每天凌晨1点执行）
     * (cron = "0 0 1 * * ?")
     */
    //@Scheduled(cron = "0 0 1 * * ?")
    public void execute() {
        //将每个deptId(潜山市，乡镇，村)的首页都存入redis
        JSONObject results = new JSONObject(16);
        JSONObject resultz = new JSONObject(16);
        JSONObject resultc = new JSONObject(16);
        String startTime = DateUtils.getTodayStartStr();
        String endTime = DateUtils.getTodayEndStr();

        Timestamp s = Timestamp.valueOf(startTime);
        Timestamp e = Timestamp.valueOf(endTime);
        //潜山市
        List<SysDept> allDepts = remoteDeptService.listChildrenDepts(1L);
        results.put("dqdw", "潜山市");
        //所有乡镇集合
        List<SysDept> townsDepts = new ArrayList<>(16);

        for (SysDept allDept : allDepts) {
            if (isEmpty(allDept.getParentId())) {
                continue;
            }
            if (allDept.getParentId() == (1L)) {
                townsDepts.add(allDept);
            }
        }
        results.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);
                }
            }
        }
        results.put("cun", isEmpty(cunDepts) ? 0 : cunDepts.size());
        //查找潜山市户籍人口总数
        List<Czrk> czrkList = czrkMapper.getAllCzrkRegionIdHj("340882000000");
        if (czrkList == null) {
            czrkList = new ArrayList<>();
        }
        //潜山市户籍人口总数
        int hjzrs = czrkList.size();

        //潜山市 户籍人口今日新增
        int hjxz = 0;
        //潜山市 户籍人口今日减少
        int hjjs = 0;

        //循环所有人判断当前总人数，该镇 户籍人口今日新增，该镇 户籍人口今日减少
        for (Czrk czrk : czrkList) {
            if (!"1".equals(czrk.getStatus())) {
                hjzrs--;
            }
            //判断是否是在今天操作的人员信息
            if (s.before(czrk.getUpdateTime()) && czrk.getUpdateTime().before(e)) {
                if (!"1".equals(czrk.getStatus())) {
                    hjjs++;
                } else {
                    hjxz++;
                }
            }
        }
        //潜山市总人数
        results.put("hjzrs", hjzrs);
        //潜山市新增
        results.put("hjxz", hjxz);
        //潜山市减少
        results.put("hjjs", hjjs);

        results.put("hjbfb", NumberUtils.percent(hjzrs, hjzrs));

        //查找潜山市常驻人口信息
        List<CzrkJzdz> czrkJzdzList = czrkJzdzService.selectCzrkJzdzListByRegionId("340882000000");
        if (czrkJzdzList == null) {
            czrkJzdzList = new ArrayList<>();
        }
        //潜山市居住人口总数
        int czzrs = czrkJzdzList.size();

        //潜山市居住人口今日新增
        int czxz = 0;
        //潜山市居住人口今日减少
        int czjs = 0;

        //循环所有人判断当前总人数，该镇 户籍人口今日新增，该镇 户籍人口今日减少
        for (CzrkJzdz czrkJzdz : czrkJzdzList) {
            if ("N".equals(czrkJzdz.getStatus())) {
                czzrs--;
            }
            //判断是否是在今天操作的人员信息
            if (s.before(czrkJzdz.getUpdateTime()) && czrkJzdz.getUpdateTime().before(e)) {
                if ("N".equals(czrkJzdz.getStatus())) {
                    czjs++;
                } else {
                    czxz++;
                }
            }
        }
        //潜山市总人数
        results.put("czzrs", czzrs);
        //潜山市新增
        results.put("czxz", czxz);
        //潜山市减少
        results.put("czjs", czjs);
        results.put("czbfb", NumberUtils.percent(czzrs, czzrs));


        /*List<Long> deptIdList = null;
        int zrs = czrkMapper.countAll(); // 总人数
        int hjzrs = czrkMapper.countHj1(deptIdList); // 该镇户籍人口总数
        //潜山市总人数
        results.put("hjzrs", hjzrs);
        int hjxz = czrkMapper.countByHjXz1(startTime, endTime, deptIdList); // 该镇 户籍人口今日新增
        //潜山市新增
        results.put("hjxz", hjxz);
        int hjjs = czrkMapper.countByHjJs1(startTime, endTime, deptIdList); // 该镇 户籍人口今日减少
        results.put("hjjs", hjjs);
        results.put("hjbfb", NumberUtils.percent(hjzrs, zrs));*/

        /*int czzrs = czrkMapper.countCz1(deptIdList);  // 该镇常住人口总数
        results.put("czzrs", czzrs);
        int czxz = czrkMapper.countByCzXz1(startTime, endTime, deptIdList); // 该镇 常住人口今日新增
        int czjs = czrkMapper.countByCzJs1(startTime, endTime, deptIdList); // 该镇 常住人口今日减少
        results.put("czxz", czxz);
        results.put("czjs", czjs);
        results.put("czbfb", NumberUtils.percent(czzrs, zrs));*/

        // 以各个镇为单位单独处理 townsDepts
        ArrayList<JSONObject> towsDataList = new ArrayList<>(20);

        //czrkList  czrkJzdzList
        for (SysDept townsDept : townsDepts) {
            JSONObject townsResult = new JSONObject(16);
            townSts(townsResult, townsDept, czrkList, czrkJzdzList, hjzrs, czzrs);
            towsDataList.add(townsResult);
        }

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


        //镇数据存入redis
        for (SysDept townsDept : townsDepts) {
            townSts(resultz, townsDept, czrkList, czrkJzdzList, hjzrs, czzrs);
//                redisService.setCacheObject(packRedisKey("town:" + deptId), result, 1L, TimeUnit.DAYS);
            setIntoRedis(packRedisKey("town:" + townsDept.getId()), resultz);
        }

        //村数据存入redis
        for (SysDept cunDept : cunDepts) {
            Long deptId = cunDept.getId();
            String deptName = cunDept.getDeptName();
            String areaId = cunDept.getAreaId();
            resultc.put("dqdw", deptName);

            //查找村的数据
            if (czrkList == null) {
                czrkList = new ArrayList<>();
            }
            //该村户籍人口总数
            int hjzrsc = 0;

            //该村 户籍人口今日新增
            int hjxzc = 0;
            //该村 户籍人口今日减少
            int hjjsc = 0;

            //循环所有人判断当前总人数，该村 户籍人口今日新增，该镇 户籍人口今日减少
            for (Czrk czrk : czrkList) {
                if (StringUtils.isNotEmpty(czrk.getVillageId()) && czrk.getVillageId().equals(areaId)) {
                    if ("1".equals(czrk.getStatus())) {
                        hjzrsc++;
                    }
                    //判断是否是在今天操作的人员信息
                    if (s.before(czrk.getUpdateTime()) && czrk.getUpdateTime().before(e)) {
                        if (!"1".equals(czrk.getStatus())) {
                            hjjsc++;
                        } else {
                            hjxzc++;
                        }
                    }
                }
            }
            resultc.put("hjzrs", hjzrsc);
            resultc.put("hjxz", hjxzc);
            resultc.put("hjjs", hjjsc);
            resultc.put("hjbfb", NumberUtils.percent(hjzrs, czzrs));


            if (czrkJzdzList == null) {
                czrkJzdzList = new ArrayList<>();
            }
            //该镇户籍人口总数
            int czzrsc = 0;

            //该镇 户籍人口今日新增
            int czxzc = 0;
            //该镇 户籍人口今日减少
            int czjsc = 0;

            //循环所有人判断当前总人数，该镇 户籍人口今日新增，该镇 户籍人口今日减少
            for (CzrkJzdz czrkJzdz : czrkJzdzList) {
                if (StringUtils.isNotEmpty(czrkJzdz.getVillageId()) && czrkJzdz.getVillageId().equals(areaId)) {
                    if ("Y".equals(czrkJzdz.getStatus())) {
                        czzrsc++;
                    }
                    //判断是否是在今天操作的人员信息
                    if (s.before(czrkJzdz.getUpdateTime()) && czrkJzdz.getUpdateTime().before(e)) {
                        if ("N".equals(czrkJzdz.getStatus())) {
                            czjsc++;
                        } else {
                            czxzc++;
                        }
                    }
                }

            }
            resultc.put("czzrs", czzrsc);
            resultc.put("czxz", czxzc);
            resultc.put("czjs", czjsc);
            resultc.put("czbfb", NumberUtils.percent(czzrs, czzrs));



            /*List<SysDept> depts = remoteDeptService.listChildrenDepts(deptId);
            resultc.put("dqdw", deptName);
            List<Long> cdeptIdList = map(depts, SysDept::getId);
            int zrsc = czrkMapper.countAll(); // 总人数
            int hjzrsc = czrkMapper.countHj1(cdeptIdList); // 该镇户籍人口总数
            resultc.put("hjzrs", hjzrsc);
            int hjxzc = czrkMapper.countByHjXz1(startTime, endTime, cdeptIdList); // 该镇 户籍人口今日新增
            resultc.put("hjxz", hjxzc);
            int hjjsc = czrkMapper.countByHjJs1(startTime, endTime, cdeptIdList); // 该镇 户籍人口今日减少
            resultc.put("hjjs", hjjsc);
            resultc.put("hjbfb", NumberUtils.percent(hjzrs, zrs));

            int czzrsc = czrkMapper.countCz1(cdeptIdList);  // 该镇常住人口总数
            resultc.put("czzrs", czzrsc);
            int czxzc = czrkMapper.countByCzXz1(startTime, endTime, cdeptIdList); // 该镇 常住人口今日新增
            int czjsc = czrkMapper.countByCzJs1(startTime, endTime, cdeptIdList); // 该镇 常住人口今日减少
            resultc.put("czxz", czxzc);
            resultc.put("czjs", czjsc);
            resultc.put("czbfb", NumberUtils.percent(czzrsc, zrsc));*/
            setIntoRedis(packRedisKey("village:" + deptId), resultc);
        }


        System.out.println("定时任务");
    }

    private void townSts(JSONObject result, SysDept sysDept, List<Czrk> czrkList, List<CzrkJzdz> czrkJzdzList, int shjzrs, int sczzrs) {
        String startTime = DateUtils.getTodayStartStr();
        String endTime = DateUtils.getTodayEndStr();
        Timestamp s = Timestamp.valueOf(startTime);
        Timestamp e = Timestamp.valueOf(endTime);
        Long deptId = sysDept.getId();
        String deptName = sysDept.getDeptName();
        String areaId = sysDept.getAreaId();
        // 乡镇以下的所有部门
        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());

        /** **/
        /*int zrs = 0; // 总人数
        if (BooleanUtils.isTrue(percent)) {
            zrs = czrkMapper.countAll();
        }*/

        if (czrkList == null) {
            czrkList = new ArrayList<>();
        }
        //该镇户籍人口总数
        int hjzrs = 0;

        //该镇 户籍人口今日新增
        int hjxz = 0;
        //该镇 户籍人口今日减少
        int hjjs = 0;

        //循环所有人判断当前总人数，该镇 户籍人口今日新增，该镇 户籍人口今日减少
        for (Czrk czrk : czrkList) {
            if (StringUtils.isNotEmpty(czrk.getVillageTownsId()) && String.valueOf(czrk.getVillageTownsId()).equals(areaId)) {
                if ("1".equals(czrk.getStatus())) {
                    hjzrs++;
                }
                //判断是否是在今天操作的人员信息
                if (s.before(czrk.getUpdateTime()) && czrk.getUpdateTime().before(e)) {
                    if (!"1".equals(czrk.getStatus())) {
                        hjjs++;
                    } else {
                        hjxz++;
                    }
                }
            }
        }
        result.put("hjzrs", hjzrs);
        result.put("hjxz", hjxz);
        result.put("hjjs", hjjs);
        result.put("hjbfb", NumberUtils.percent(hjzrs, shjzrs));


        if (czrkJzdzList == null) {
            czrkJzdzList = new ArrayList<>();
        }
        //该镇户籍人口总数
        int czzrs = 0;

        //该镇 户籍人口今日新增
        int czxz = 0;
        //该镇 户籍人口今日减少
        int czjs = 0;

        //循环所有人判断当前总人数，该镇 户籍人口今日新增，该镇 户籍人口今日减少
        for (CzrkJzdz czrkJzdz : czrkJzdzList) {
            if (StringUtils.isNotEmpty(czrkJzdz.getTownId()) && czrkJzdz.getTownId().equals(areaId)) {
                if ("Y".equals(czrkJzdz.getStatus())) {
                    czzrs++;
                }
                //判断是否是在今天操作的人员信息
                if (s.before(czrkJzdz.getUpdateTime()) && czrkJzdz.getUpdateTime().before(e)) {
                    if ("N".equals(czrkJzdz.getStatus())) {
                        czjs++;
                    } else {
                        czxz++;
                    }
                }
            }

        }
        result.put("czzrs", czzrs);
        result.put("czxz", czxz);
        result.put("czjs", czjs);
        result.put("czbfb", NumberUtils.percent(czzrs, sczzrs));

        /*int czzrs = czrkMapper.countCz1(deptIdList);  // 该镇常住人口总数
        result.put("czzrs", czzrs);
        int czxz = czrkMapper.countByCzXz1(startTime, endTime, deptIdList); // 该镇 常住人口今日新增
        int czjs = czrkMapper.countByCzJs1(startTime, endTime, deptIdList); // 该镇 常住人口今日减少
        result.put("czxz", czxz);
        result.put("czjs", czjs);
        result.put("czbfb", NumberUtils.percent(czzrs, zrs));*/

        result.put("zhen", deptName);
        /** **/


        // 常住人口信息
//        int type = 4; // 乡镇
//        int czzrs = czrkMapper.countCzrk(type, areaId); // 常住人口
//        result.put("czzrs", czzrs);
//
//        int zrs = 0;
//        // 常住人口占总人口的百分比
//        if (BooleanUtils.isTrue(percent)) {
//             // 查全部
//            zrs = czrkMapper.countCzrk(type, areaId);
//            String czbfb = NumberUtils.percent(czzrs, zrs);
//            result.put("czbfb", czbfb);
//        }
//
////        type = 4;
//        int czxz = czrkMapper.countByCzXz(startTime, endTime, type, areaId);
//        int czjs = czrkMapper.countByCzJs(startTime, endTime, type, areaId);
//        result.put("czxz", czxz);
//        result.put("czjs", czjs);
//
//        result.put("zhen", deptName);
//
//        // 户籍人口信息
//        int hjxz = czrkMapper.countByHjXz(startTime, endTime, type, areaId); // 新增
//        int hjjs = czrkMapper.countByHjJs(startTime, endTime, type, areaId);// 减少
//        result.put("hjxz", hjxz);
//        result.put("hjjs", hjjs);
//
//        // 户籍总人数
//        int hjzrs = czrkMapper.countHj(startTime, endTime, type, areaId);
////                int hjzrs= isEmpty(hjzrsList) ? 0 : hjzrsList.size();
//        result.put("hjzrs", hjzrs);
//        String hjbfb = NumberUtils.percent(hjzrs, zrs);
//        result.put("hjbfb", hjbfb);
    }

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

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

    /***
     * 新生儿（每天18点执行）
     *
     */
    //@Scheduled(cron = "0 0 18 * * ?")
    public void getNewborn() {

        String token = getToken();


        if (StringUtils.isNotBlank(token)) {

            String startTime = redisService.getCacheObject("startTimeNew");
            if (StringUtils.isEmpty(startTime)) {
                startTime = "2022-04-01 00:00:00.0";
            }
            String endTime = DateUtils.formatString(new Date());
            redisService.setCacheObject("startTimeNew", endTime);
            endTime = endTime.replace(" ", "%20");
            startTime = startTime.replace(" ", "%20");

            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("client_id", "acdf50bd13be4901b64c62b1fee862c0");
            paramMap.put("access_token", token);
            paramMap.put("xzqh", "潜山市");
            paramMap.put("start_time", startTime);
            paramMap.put("end_time", endTime);
            String http = "http://60.171.171.235:9090/service/api/rkk/qxcsyxzmcx";
            try {
                String data = HttpClientUtils.doGet(http, paramMap);

                List<BirthRecords> birthRecordsList = JSONObject.parseArray(data, BirthRecords.class);
                for (BirthRecords birthRecords : birthRecordsList) {
                    birthRecords.setIsDel("N");
                    birthRecords.setCreateBy("系统");
                    birthRecords.setUpdateBy("系统");
                    birthRecords.setStatus(1);
                }
                //批量保存
                birthRecordsService.insertListBirthRecords(birthRecordsList);
                System.out.println(data);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 获取政务网token
     */
    public String getToken() {
        String token = "";
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("client_id", "acdf50bd13be4901b64c62b1fee862c0");
        paramMap.put("client_secret", "a3650d67fc034b2d8ea259182b3d99f3");
        String http = "http://60.171.171.235:9090/oauth/token";
        try {
            String data = HttpClientUtils.doGet(http, paramMap);
            JSONObject jsonObject = JSONObject.parseObject(data);
            token = jsonObject.getString("access_token");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return token;
    }

    /**
     * 抓取核酸数据每10分钟抓取一次,新增到accounting_data
     */
    //@Scheduled(cron = "0 0/10 * * * ? ")
    public void insertAccountingData() {
        String token = getToken();
        if (StringUtils.isNotBlank(token)) {
            String startTime = "2022-05-14 00:00:00.0";
            //去数据库取最新的一条数据
            AccountingDataVo accountingData = accountingDataService.getAccountingDataOne();
            if (accountingData != null) {
                startTime = accountingData.getCjsj();
                Date parse = DateUtil.parse(startTime);
                Date parseNew = DateUtil.offsetSecond(parse, 1);
                startTime = DateUtil.format(parseNew, "yyyy-MM-dd HH:mm:ss");
            }
            //String startTime = redisService.getCacheObject("startTime");
            //String startTime = "2022-05-14 10:47:00.0";
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("client_id", "acdf50bd13be4901b64c62b1fee862c0");
            paramMap.put("access_token", token);
            paramMap.put("sfzhm", "");
            if (StringUtils.isBlank(startTime)) {
                //第一次抓取当前时间到之前的10分钟的数据
                Date nowDate = DateUtils.getNowDate();
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String endTime = format.format(nowDate);
                startTime = DateUtils.plusSeconds(endTime, 10);
                redisService.setCacheObject("startTime", endTime);
            }
            String endTime = DateUtils.formatString(new Date());
            redisService.setCacheObject("startTime", endTime);
            endTime = endTime.replace(" ", "%20");
            startTime = startTime.replace(" ", "%20");
            paramMap.put("start_time", startTime);
            paramMap.put("end_time", endTime);
            String http = "http://60.171.171.235:9090/service/api/wjw/qshssjsjc";
            try {
                String data = HttpClientUtils.doGet(http, paramMap);

                if (StringUtils.isNotBlank(data)) {
                    List<AccountingDataVo> list = JSONObject.parseArray(data, AccountingDataVo.class);
                    if (list != null && list.size() > 0) {
                        //插入数据
                        //accountingDataService.insertAccountingData(list);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //@Scheduled(cron = "0 0/10 * * * ? ")
    public void thirdNucleicAcid() {
        String startTime = redisService.getCacheObject("startTime");
        if (StringUtils.isEmpty(startTime)) {
            startTime = "2022-05-14 00:00:00";
        }
        //开始时间往后推10分钟
        String endTime = DateUtils.plusSeconds(startTime, 10);

        accountingDataService.thirdNucleicAcid(startTime, endTime);

        redisService.setCacheObject("startTime", endTime);

    }


    /***
     *  匹配核酸和户籍数据
     */
    public void pphshj() {
        //String startTime = "2022-05-14 00:00:00.0";
        String startTime = redisService.getCacheObject("startTime");
        if (StringUtils.isBlank(startTime)) {
            startTime = "2022-05-14 00:00:00.0";
        }

        Date parse = DateUtil.parse(startTime);
        Date parseNew = DateUtil.offsetSecond(parse, 600);
        String endTime = DateUtil.format(parseNew, "yyyy-MM-dd HH:mm:ss");
        redisService.setCacheObject("startTime", endTime);

        System.out.println("batchInsert 查询数据开始========");
        long start1 = System.currentTimeMillis();
        //获取所有核酸数据源
        List<TSampling514> TSampling514List = accountingDataService.getTSampling514AllData(startTime, endTime);
        //获取所有户籍数据
        //List<Czrk> czrks = czrkMapper.listByCzrk(new Czrk());

        long end1 = System.currentTimeMillis();
        System.out.println("---------------查询数据耗时" + (end1 - start1) + "---------------");

        //List<Czrk> czrkList = new ArrayList<>();
        System.out.println("batchInsert 循环数据开始========");
        long start2 = System.currentTimeMillis();
        for (TSampling514 tSampling514 : TSampling514List) {
            if (tSampling514.getCollectTime() != null) {
                Czrk czrk = new Czrk();
                czrk.setNucleicAcidTime(String.valueOf(tSampling514.getCollectTime()));
                czrk.setIdCard(tSampling514.getIdCard());
                czrkMapper.updateCzrkByNucleicAcid(czrk);
                //czrkList.add(czrk);
            }

        }

        long end2 = System.currentTimeMillis();
        System.out.println("---------------循环数据耗时" + (end2 - start2) + "---------------");
    }


    public void pphshjNo() {

        System.out.println("batchInsert 查询数据开始========");
        long start1 = System.currentTimeMillis();
        //获取所有核酸数据源
        List<TSampling514> TSampling514List = accountingDataService.getTSampling514AllDataNoTime();
        //获取所有户籍数据
        //List<Czrk> czrks = czrkMapper.listByCzrk(new Czrk());

        long end1 = System.currentTimeMillis();
        System.out.println("---------------查询数据耗时" + (end1 - start1) + "---------------");

        //List<Czrk> czrkList = new ArrayList<>();
        System.out.println("batchInsert 循环数据开始========");
        long start2 = System.currentTimeMillis();
        for (TSampling514 tSampling514 : TSampling514List) {
            Czrk czrk = new Czrk();
            czrk.setNucleicAcidTime("-");
            czrk.setIdCard(tSampling514.getIdCard());
            czrkMapper.updateCzrkByNucleicAcid(czrk);
            //czrkList.add(czrk);

        }

        long end2 = System.currentTimeMillis();
        System.out.println("---------------循环数据耗时" + (end2 - start2) + "---------------");
    }


    /***
     * 核酸统计(每一个小时跑一次)
     */
    //@Scheduled(cron = "0 0 * * * ? ")
    public void nucleicAcidStatistics() {

        System.out.println("batchInsert 核酸统计开始开始========");
        long start = System.currentTimeMillis();
        //潜山市
        JSONObject resultsS = new JSONObject(16);
        //镇
        JSONObject resultsZ = new JSONObject(16);
        //村
        JSONObject resultsC = new JSONObject(16);

        //SysUser sysUser = AuthUtils.getLoginUser().getSysUser();
        //SysDept dept = sysUser.getDept();

        List<SysDept> allDepts = remoteDeptService.listChildrenDepts(1L);
        //查找户籍人口总数
        List<Czrk> czrkList = czrkMapper.getAllCzrkRegionId("340882000000");

        //所有乡镇集合
        List<SysDept> townsDepts = new ArrayList<>(16);

        for (SysDept allDept : allDepts) {
            if (isEmpty(allDept.getParentId())) {
                continue;
            }
            if (allDept.getParentId() == (1L)) {
                townsDepts.add(allDept);
            }
        }

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

        resultsS.put("townDatas", towsDataList);
        resultsS.put("type", "1");

        redisService.setCacheObject("1", resultsS);


        //获取镇数据
        for (SysDept townsDept : townsDepts) {

            //所有乡镇集合
            List<SysDept> cunDepts = new ArrayList<>(16);

            for (SysDept allDept : allDepts) {
                if (isEmpty(allDept.getParentId())) {
                    continue;
                }
                if (allDept.getParentId() == Long.valueOf(townsDept.getId())) {
                    cunDepts.add(allDept);
                }
            }

            ArrayList<JSONObject> cunDataList = new ArrayList<>(20);

            for (SysDept cunDept : cunDepts) {
                JSONObject townsResult = new JSONObject(16);
                townStsvaccineCun(townsResult, cunDept, czrkList);
                cunDataList.add(townsResult);
            }

            resultsZ.put("townDatas", cunDataList);
            resultsZ.put("type", "2");

            redisService.setCacheObject(townsDept.getAreaId(), resultsZ);
        }
        long end = System.currentTimeMillis();
        System.out.println("---------------核酸统计耗时" + (end - start) + "---------------");

    }

    private void townStsvaccine(JSONObject result, SysDept sysDept, List<Czrk> czrkList) {
        String deptName = sysDept.getDeptName();
        String areaId = sysDept.getAreaId();

        if (czrkList == null) {
            czrkList = new ArrayList<>();
        }

        //该镇户籍人口总数
        int hjzrs = 0;

        //该镇 接种人员数据
        int hjymjz = 0;

        //循环所有人判断当前总人数，该镇 户籍人口今日新增，该镇 户籍人口今日减少
        for (Czrk czrk : czrkList) {
            if (StringUtils.isNotEmpty(czrk.getVillageTownsIdXjd()) && String.valueOf(czrk.getVillageTownsIdXjd()).equals(areaId)) {
                if ("1".equals(czrk.getStatus())) {
                    hjzrs++;
                }

                if ("Y".equals(czrk.getIsNucleicAcid())) {
                    hjymjz++;
                }
            }
        }
        result.put("hjzrs", hjzrs);
        result.put("hjymjz", hjymjz);
        result.put("hjbfb", NumberUtils.percent(hjymjz, hjzrs));
        result.put("name", deptName);
    }

    private void townStsvaccineCun(JSONObject result, SysDept sysDept, List<Czrk> czrkList) {

        ArrayList<JSONObject> towsDataList = new ArrayList<>(20);
        JSONObject resultsC = new JSONObject(16);

        String deptName = sysDept.getDeptName();
        String areaId = sysDept.getAreaId();

        if (czrkList == null) {
            czrkList = new ArrayList<>();
        }

        //该村户籍人口总数
        int hjzrs = 0;

        //该村接种人员数据
        int hjymjz = 0;

        //循环所有人判断当前总人数，该镇 户籍人口今日新增，该镇 户籍人口今日减少
        for (Czrk czrk : czrkList) {
            if (StringUtils.isNotEmpty(czrk.getVillageIdXjd()) && String.valueOf(czrk.getVillageIdXjd()).equals(areaId)) {
                if ("1".equals(czrk.getStatus())) {
                    hjzrs++;
                }

                if ("Y".equals(czrk.getIsNucleicAcid())) {
                    hjymjz++;
                }
            }
        }
        result.put("hjzrs", hjzrs);
        result.put("hjymjz", hjymjz);
        result.put("hjbfb", NumberUtils.percent(hjymjz, hjzrs));
        result.put("name", deptName);

        towsDataList.add(result);
        resultsC.put("townDatas", towsDataList);
        resultsC.put("type", "3");
        redisService.setCacheObject(areaId, resultsC);
    }

    public void upStarTime(String starTim) {
        redisService.setCacheObject("toQianShanStartTime", starTim);
    }

    /**
     * 新增
     *
     * @param accountingDataList
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    @Master
    public int insertAccountingData(List<AccountingDataVo> accountingDataList) {
        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
        AccountingDataMapper mapper = sqlSession.getMapper(AccountingDataMapper.class);

        System.out.println("batchInsert 插入开始========");
        long start = System.currentTimeMillis();
        Czrk czrk = new Czrk();

        for (AccountingDataVo accountingData : accountingDataList) {
            String zjhm = accountingData.getZjhm();
            if (StringUtils.isNotBlank(zjhm)) {
                czrk.setIdCard(zjhm);
                czrk.setNucleicAcidTime(accountingData.getCjsj());
                //去更新常住人口表中数据
                czrkMapper.updateCzrkByNucleicAcid(czrk);
            }
            String mainKey = accountingData.getMainKey();
            accountingData.setId(mainKey);
            int result = mapper.selectById(mainKey);
            if (result == 0) {
                accountingData.setId(mainKey);
                mapper.insertAccountingData(accountingData);
            }
        }

        sqlSession.flushStatements();
        long end = System.currentTimeMillis();
        System.out.println("---------------插入核酸数据耗时" + (end - start) + "---------------");
        return 0;
    }


    /***
     * 来宜数据匹配(每个小时的35分开始跑数据)
     */
    @SneakyThrows
    //@Scheduled(cron = "0 35 * * * ? ")
    public void toQianshanData() {
        System.out.println("batchInsert 来宜人员插入开始========");
        long start = System.currentTimeMillis();

        String token = getToken();
        if (StringUtils.isNotBlank(token)) {

            //String startTime = redisService.getCacheObject("toQianShanStartTime");
            //if (StringUtils.isEmpty(startTime)) {
                //startTime = "2022-05-14 00:00:00";
            //}

            //数据库查询最新数据
            ToQianshanPersonner toQianshanPersonner = toQianshanPersonnerService.getNewInfo();
            String startTime = "2022-05-1 00:00:00";
            if(toQianshanPersonner != null){
                startTime = toQianshanPersonner.getHiDate();
            }

            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date =df.parse(startTime);
            date.setTime(date.getTime() + 1000);
            startTime = df.format(date);


            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("client_id", "acdf50bd13be4901b64c62b1fee862c0");
            paramMap.put("access_token", token);
            paramMap.put("rc", "");
            paramMap.put("area", "潜山");

            String endTime = DateUtils.formatString(new Date());
            //redisService.setCacheObject("toQianShanStartTime", endTime);
            endTime = endTime.replace(" ", "%20");
            startTime = startTime.replace(" ", "%20");
            paramMap.put("djsjqs", startTime);
            paramMap.put("djsjjs", endTime);
            String http = "http://60.171.171.235:9090/service/api/rkk/qslyrysj";
            try {
                String data = HttpClientUtils.doGet(http, paramMap);

                if (StringUtils.isNotBlank(data)) {
                    List<ToQianshanPersonner> list = JSONObject.parseArray(data, ToQianshanPersonner.class);
                    if (list != null && list.size() > 0) {
                        //插入数据
                        toQianshanPersonnerService.insertToQianshanPersonner(list);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        long end = System.currentTimeMillis();
        System.out.println("---------------插入来宜人员数据耗时" + (end - start) + "---------------");
    }

}
