package com.zcloud.service.specheck.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zcloud.entity.Page;
import com.zcloud.entity.PageData;
import com.zcloud.mapper.datasource.specheck.*;
import com.zcloud.service.specheck.SpecheckService;
import com.zcloud.util.*;
import com.zcloud.util.docking.AesGcm256Util;
import com.zcloud.util.docking.HttpClientUtil;
import com.zcloud.util.docking.ConstCorps;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class SpecheckServiceImpl implements SpecheckService {

    @Resource
    private SpeCheckTaskMapper speCheckTaskMapper;
    @Resource
    private SpeCheckSourceMapper speCheckSourceMapper;
    @Resource
    private SpeCheckHiddenMapper speCheckHiddenMapper;
    @Resource
    private SpeCheckRecordMapper speCheckRecordMapper;
    @Resource
    private SpeBusHiddenMapper busHiddenMapper;


    @Resource
    private RedisUtil redisUtil;

    @Override
    public List<PageData> getCheckTask(Page page) {
//        PageData parameters = page.getPd();
//        String corpCode = ConstCorps.getcorpCodeById(Jurisdiction.getCORPINFO_ID());
        String corpCode = ConstCorps.getcorpCodeById(Jurisdiction.getCORPINFO_ID());
        if (Tools.isEmpty(corpCode)) {
            page.setTotalResult(0);
            return Collections.emptyList();
        }
        String token = ConstCorps.getTokenByCorpId(Jurisdiction.getCORPINFO_ID());
        JSONObject parms = new JSONObject();
        // 对应上编码
        parms.put("companyCodes", Collections.singletonList(ConstCorps.getcorpCodeById(Jurisdiction.getCORPINFO_ID())));
        HttpClientUtil httpClientUtil = new HttpClientUtil();
        JSONObject resJsonData = httpClientUtil.doPost("/taskSys/busi/syf/getCheckTask", token, parms.toString());
        List<PageData> apiProcessingData = getApiProcessingData(resJsonData, page, 1);
        List<String> taskIdList = apiProcessingData.stream().map((item) -> item.getString("id")).collect(Collectors.toList());
        List<PageData> countTaskList = speCheckTaskMapper.getCheckCount(taskIdList);
        List<PageData> waitForRetDataList = getApiProcessingData(resJsonData, page, 1);
        waitForRetDataList.forEach((item) -> {
            Optional<PageData> first = countTaskList.stream().filter((countItem) -> countItem.getString("taskId").equals(item.getString("id"))).findFirst();
            item.put("reportAllCount", 0);
            item.put("reportSuccessCount", 0);
            if (first.isPresent()) {
                item.put("reportAllCount", first.get().get("reportAllCount"));
                item.put("reportSuccessCount", first.get().get("reportSuccessCount"));
            }
        });
//        speCheckTaskMapper.
        return waitForRetDataList;
    }

    @Override
    public List<PageData> getCheckItem(Page page) {
        String token = ConstCorps.getTokenByCorpId(Jurisdiction.getCORPINFO_ID());
        PageData ftParms = page.getPd();
        JSONObject parms = new JSONObject();
        JSONObject pageParm = new JSONObject();
        pageParm.put("current", 1);
        pageParm.put("size", 1000);
        parms.put("page", pageParm);
        parms.put("taskId", ftParms.getString("taskId"));
        HttpClientUtil httpClientUtil = new HttpClientUtil();
        JSONObject resJsonData = httpClientUtil.doPost("/taskSys/busi/syf/getCheckItem", token, parms.toString());
        return getApiProcessingData(resJsonData, page, 2);
    }

    @Override
    public List<PageData> getCheckScore(Page page) {
        String token = ConstCorps.getTokenByCorpId(Jurisdiction.getCORPINFO_ID());
        PageData ftParms = page.getPd();
        JSONObject parms = new JSONObject();
        JSONObject pageParm = new JSONObject();
        pageParm.put("current", 1);
        pageParm.put("size", 1000);
        parms.put("page", pageParm);
        parms.put("taskId", ftParms.getString("taskId"));
        parms.put("checkItemId", ftParms.getString("checkItemId"));
        HttpClientUtil httpClientUtil = new HttpClientUtil();
        JSONObject resJsonData = httpClientUtil.doPost("/taskSys/busi/syf/getCheckScore", token, parms.toString());

        return getApiProcessingData(resJsonData, page, 3);

//        return getApiProcessingData(resJsonData, page, 3);
    }

    @Override
    @Transactional
    @Deprecated
    public void receiveCheckRecordList(PageData pageData) {
//        String token = ConstCorps.getToken(Jurisdiction.getCORPINFO_ID());
        // 任务
        PageData checkTask = JSONObject.parseObject(pageData.getString("checkTask"), PageData.class);
        initOperation(checkTask);
        // 回参不为 null 并且 obj的值不为空
        checkTask.put("taskId", checkTask.getString("id"));
        PageData byId = speCheckTaskMapper.findById(checkTask);
        if (byId == null) {
            // 相同的任务只在表里存一次
            speCheckTaskMapper.save(checkTask);
        }
        // 记录
        PageData checkRecord = JSONObject.parseObject(pageData.getString("checkRecord"), PageData.class);
        checkRecord.put("taskId", checkTask.getString("taskId"));
        checkRecord.put("checkContent", JSONObject.toJSONString(checkRecord.get("checkContent")));
        String specheckRecordId = UUID.randomUUID().toString();
        checkRecord.put("specheckRecordId", specheckRecordId);
        initOperation(checkRecord);
        // 转成要对接的数据
        PageData convertData = convertIntoDataToReport(checkRecord);
        JSONArray waitFreportRecord = new JSONArray();
        waitFreportRecord.add(convertData);
        System.out.println(waitFreportRecord);
        String encrypt = AesGcm256Util.encrypt(waitFreportRecord.toString(), AesGcm256Util.hexToByte(ConstCorps.KEY), AesGcm256Util.hexToByte(ConstCorps.IV));
        System.out.println(encrypt);
        JSONObject parms = new JSONObject();
        parms.put("data", encrypt);
        String token = ConstCorps.getTokenByCorpId(Jurisdiction.getCORPINFO_ID());
        HttpClientUtil httpClientUtil = new HttpClientUtil();
        // 上报接口对接
        JSONObject resJsonData = httpClientUtil.doPost("/taskSys/busi/syf/receiveCheckRecordList", token, parms.toString());
        String batchId = resJsonData.getJSONObject("obj").getString("batchId");
        checkRecord.put("batchId", batchId);
        checkRecord.put("companyCode", checkTask.getString("companyCode"));
        checkRecord.put("batchStatus", 1);
        speCheckRecordMapper.save(checkRecord);
        // 添加待查询批处理结果的 上报id
        redisUtil.hset("speCheck:checkRecord", batchId, specheckRecordId);
        // 隐患
        List<PageData> hiddenInfoList = JSONObject.parseArray(pageData.getString("hiddenInfoList"), PageData.class);
        hiddenInfoList.forEach(item -> {
            String dangerId = UUID.randomUUID().toString();
            initOperation(item);
            item.put("companyCode", ConstCorps.getcorpCodeById(Jurisdiction.getCORPINFO_ID()));
            item.put("dangerId", dangerId);
            item.put("id", dangerId);
            item.put("taskId", checkTask.getString("taskId"));
            item.put("checkType", checkRecord.getString("checkType"));
            sendHidden(item);
            item.put("specheckRecordId", specheckRecordId);
            redisUtil.hset("speCheck:checkHidden", item.getString("batchId"), dangerId);
            item.put("checkScore", JSONObject.toJSONString(item.get("checkScore")));
            item.put("batchStatus", 1);
        });
        if (!hiddenInfoList.isEmpty()) speCheckHiddenMapper.saveBatch(hiddenInfoList);
    }

    private void sendHidden(PageData item) {
        String token = ConstCorps.getTokenByCorpId(Jurisdiction.getCORPINFO_ID());
        PageData data = new PageData();
        data.putAll(item);
        data.put("checkDate", data.getString("checkDate").substring(0, 10));
        data.put("checkPay", String.valueOf(data.get("checkPay")));
        data.put("id", data.getString("specheckRecordId"));
        data.remove("specheckRecordId");
        JSONArray waitFreportRecordHidden = new JSONArray();
        waitFreportRecordHidden.add(data);
        System.out.println(waitFreportRecordHidden);
        String encryptHidden = AesGcm256Util.encrypt(waitFreportRecordHidden.toString(), AesGcm256Util.hexToByte(ConstCorps.KEY), AesGcm256Util.hexToByte(ConstCorps.IV));
        JSONObject parmsHidden = new JSONObject();
        parmsHidden.put("data", encryptHidden);
        HttpClientUtil httpClientUtilHidden = new HttpClientUtil();
        JSONObject resJsonDataHidden = httpClientUtilHidden.doPost("/taskSys/busi/syf/receiveCheckDangerList", token, parmsHidden.toString());
        String batchId = resJsonDataHidden.getJSONObject("obj").getString("batchId");
        item.put("batchId", batchId);

    }

    private PageData convertIntoDataToReport(PageData checkRecord) {
        PageData data = new PageData();
        data.putAll(checkRecord);
        data.remove("deleted");
        data.remove("checkContent");
//        UUID.nameUUIDFromBytes(pageData.getString("HIDDEN_ID").getBytes()));
        data.put("id", UUID.nameUUIDFromBytes(checkRecord.getString("specheckRecordId").getBytes()));
        data.put("checkDate", checkRecord.getString("checkDate").substring(0, 10));
        // todo 在测试环境 给个默认值
        data.put("companyCode", ConstCorps.getcorpCodeById(Jurisdiction.getCORPINFO_ID()));
        data.remove("specheckRecordId");
        data.remove("specheckTaskId");
        data.remove("specheckSourceId");
        data.remove("batchId");

        return data;
    }

    @Override
    @Transactional
    public void reportedResult(PageData pageData) {

        String batchId = pageData.getString("batchId");
//        2 处理完成且成功 batchStatus
//        3 处理完成且失败 batchStatus
        // 获取2-3一个随机数

    }

    @Override
    public List<PageData> getRecordingList(Page page) {
        return speCheckRecordMapper.datalistPage(page);
    }

    @Override
    public PageData getHiddenInfo(PageData pageData) {
        return speCheckHiddenMapper.listAllByTaskId(pageData);
    }

    @Override
    public PageData getRecordInfo(PageData pageData) {
        PageData resData = speCheckRecordMapper.getRecordInfo(pageData);
        return resData;
    }

    @Override
    public List<PageData> getReportingTask() {
        return speCheckRecordMapper.getReportingTask();
    }

    @Override
    public List<PageData> getReportingHidden() {
        return speCheckRecordMapper.getReportingHidden();
    }

    @Override
    @Transactional
    public void changStatusByBatchSql(PageData changeT2BatchStatus, PageData changeT3BatchStatus) {
        if (changeT2BatchStatus.getString("execute").equals("1")) {
            speCheckRecordMapper.changStatusByBatchSql(changeT2BatchStatus);
        }
        if (changeT3BatchStatus.getString("execute").equals("1")) {
            speCheckRecordMapper.changStatusByBatchSql(changeT3BatchStatus);
        }
    }

    // 每小时解析一次任务
    @Override
    @Transactional
    public void parsingTasksByHour() {
        // 过期任务，被删除任务查询不到
        List<PageData> taskList = getTaskListByApi();
        if (taskList.isEmpty()) {
            return;
        }
        List<PageData> waitSaveList = new ArrayList<>();
        ArrayList<PageData> waitSaveSource = new ArrayList<>();

        for (PageData item : taskList) {
            String CORPINFO_ID = ConstCorps.getcorpIdByCode(item.getString("companyCode"));
            item.put("taskId", item.getString("id"));
            item.put("corpinfoId", CORPINFO_ID);
            PageData unitSource = new PageData();
            unitSource.put("corpinfoId", CORPINFO_ID);

            for (int j = 1; j < 5; j++) {
                PageData data = new PageData();
                String specheck_task_id = UuidUtil.get32UUID();
                item.put("checkType", j);
                data.putAll(item);
                data.put("specheckTaskId", specheck_task_id);
                waitSaveList.add(data);

            }

        }
        // 处理任务
        speCheckTaskMapper.saveByBatch(waitSaveList);
        // 初始化危险源
        if (!waitSaveList.isEmpty()) {
            PageData unitSource = new PageData();
            unitSource.put("corpinfoId", Jurisdiction.getCORPINFO_ID());
            List<PageData> dangerSourceList = speCheckSourceMapper.getDangerSourceList(unitSource);
            for (PageData source : dangerSourceList) {
                PageData sourceData = new PageData();
                sourceData.put("riskunitId", source.getString("RISKUNIT_ID"));
                sourceData.put("corpinfoId", Jurisdiction.getCORPINFO_ID());
                initSaveTable(sourceData);
                PageData data = new PageData();
                data.put("corpinfoId", Jurisdiction.getCORPINFO_ID());
                List<PageData> pageData = speCheckTaskMapper.listAllTask(data);
                for (PageData task : pageData) {
                    PageData data1 = new PageData();
                    sourceData.put("specheckSourceId", UuidUtil.get32UUID());
                    sourceData.put("specheckTaskId", task.getString("specheckTaskId"));
                    data1.putAll(sourceData);
                    waitSaveSource.add(data1);
                }
            }
        }
        if (!waitSaveSource.isEmpty()) {
            speCheckSourceMapper.saveByBatch(waitSaveSource);
        }
    }


    @Override
    public List<PageData> getCheckTaskdatalistPage(Page page) {
        return speCheckTaskMapper.datalistPage(page);
    }

    @Override
    public List<PageData> getCheckSource(Page page) {
        return speCheckTaskMapper.getCheckSourcelistPage(page);
    }

    @Override
    @Transactional
    public void saveReceiveCheckRecordList(PageData pageData) {
        PageData checkRecord = JSONObject.parseObject(pageData.getString("checkRecord"), PageData.class);
        initOperation(checkRecord);
        checkRecord.put("checkContent", JSONObject.toJSONString(checkRecord.get("checkContent")));
        String specheckRecordId = UuidUtil.get32UUID();
        checkRecord.put("specheckRecordId", specheckRecordId);
        speCheckRecordMapper.save(checkRecord);
        speCheckSourceMapper.updateBySpeSourceId(checkRecord);
        // 隐患信息
        if (Tools.isEmpty(pageData.getString("hiddenInfoList"))) {
            return;
        }
        List<String> hiddenInfoList = Arrays.asList(pageData.getString("hiddenInfoList").split(","));
        // 没隐患 全部删除
        String specheckSourceId = checkRecord.getString("specheckSourceId");
        PageData data = new PageData();
        if (Tools.notEmpty(specheckSourceId)) {
            data.put("SPECHECK_SOURCE_ID", specheckSourceId);
            data.put("specheckSourceId", specheckSourceId);
            data.put("hiddenList", hiddenInfoList);
            busHiddenMapper.removeChangeHidden(data);
            speCheckHiddenMapper.removeChangeHidden(data);
        }
        data.put("specheckRecordId", specheckRecordId);
        data.put("CHECKRECORD_ID", specheckRecordId);
        speCheckHiddenMapper.addRecordIdByHiddenId(data);
        busHiddenMapper.addRecordIdByHiddenId(data);
    }

    @Override
    @Transactional
    public ReturnMap reportCurrentRecord(PageData pageData) {
        // 上报 专项检查流程
        // 1 上报 专项检查信息。 把记录id存到redis里 让定时任务去处理
        // 2 上报 双控中隐患信息。 定时任务处理 涉及到的 双控中的隐患 处理好之后 让另一个定时任务 处理 专项检查中隐患上报 如有问题 打回到流程1
        // 3 上报 专项检查中隐患信息 处理专项检查任务

        PageData record = speCheckRecordMapper.findById(pageData);
        PageData convertData = convertIntoDataToReport(record);
        JSONArray waitFreportRecord = new JSONArray();
        waitFreportRecord.add(convertData);
        System.out.println(waitFreportRecord);
        String encrypt = AesGcm256Util.encrypt(waitFreportRecord.toString(), AesGcm256Util.hexToByte(ConstCorps.KEY), AesGcm256Util.hexToByte(ConstCorps.IV));
        System.out.println(encrypt);
        JSONObject parms = new JSONObject();
        parms.put("data", encrypt);
        String token = ConstCorps.getTokenByCorpId(Jurisdiction.getCORPINFO_ID());
        HttpClientUtil httpClientUtil = new HttpClientUtil();
        JSONObject resJsonData = httpClientUtil.doPost("/taskSys/busi/syf/receiveCheckRecordList", token, parms.toString());
        String batchId = resJsonData.getJSONObject("obj").getString("batchId");
        record.put("batchId", batchId);
        record.put("batchStatus", 1);
        speCheckRecordMapper.changebatchStatus(record);
        // 移除掉 没有specheckRecordId 的隐患 没有specheckRecordId 是没保存的隐患
        speCheckHiddenMapper.removeNoHasRecordId(record);

        // 修改记录上报状态
        redisUtil.hset("speCheck:checkRecord:" + Jurisdiction.getCORPINFO_ID(),
                batchId,
                record.getString("specheckRecordId"));
        return ReturnMap.ok();
    }

    @Override
    @Transactional
    public void editReceiveCheckRecordList(PageData pageData) {
        PageData checkRecord = JSONObject.parseObject(pageData.getString("checkRecord"), PageData.class);
        initOperation(checkRecord);
        checkRecord.put("checkContent", JSONObject.toJSONString(checkRecord.get("checkContent")));
        speCheckRecordMapper.edit(checkRecord);

        // 隐患信息
        List<String> hiddenInfoList = Arrays.asList(pageData.getString("hiddenInfoList").split(","));
        if (hiddenInfoList.size() == 1 && hiddenInfoList.get(0).equals("")) {
            hiddenInfoList = null;
        }
        String specheckSourceId = checkRecord.getString("specheckSourceId");
        if (Tools.notEmpty(specheckSourceId)) {
            PageData data = new PageData();
            data.put("SPECHECK_SOURCE_ID", specheckSourceId);
            data.put("SPECHECK_TASK_ID", checkRecord.getString("specheckTaskId"));
            data.put("specheckSourceId", checkRecord.getString("specheckSourceId"));
            data.put("specheckRecordId", checkRecord.getString("specheckRecordId"));
            data.put("hiddenList", hiddenInfoList);
            busHiddenMapper.removeChangeHidden(data);
            busHiddenMapper.changeHiddenCheckrecordId(data);
            speCheckHiddenMapper.removeChangeHidden(data);
        }
    }

    @Override
    @Transactional
    public void addHidden(PageData pd) {
        busHiddenMapper.addHidden(pd);
        initOperation(pd);
        speCheckHiddenMapper.saveHiddenByStaging(pd);
    }

    @Override
    @Transactional
    public void editHidden(PageData pd) {
        busHiddenMapper.editHidden(pd);
        initOperation(pd);
        speCheckHiddenMapper.editHiddenByStaging(pd);
    }

    @Override
    @Transactional
    public void removeHidden(PageData pd) {
        busHiddenMapper.removeHidden(pd);
        speCheckHiddenMapper.removeHiddenStaging(pd);
    }

    @Override
    public ReturnMap getTasksToChecked(PageData pageData) {
//        PageData pd = speCheckTaskMapper.getTasksToChecked(pageData);

        return null;
    }


    private List<PageData> getTaskListByApi() {
        String token = ConstCorps.getTokenByCorpId(Jurisdiction.getCORPINFO_ID());
        JSONObject parms = new JSONObject();
        // 对应上编码
        if (Tools.isEmpty(ConstCorps.getcorpCodeById(Jurisdiction.getCORPINFO_ID()))) {
            return Collections.emptyList();
        }
        parms.put("companyCodes", Arrays.asList(ConstCorps.getcorpCodeById(Jurisdiction.getCORPINFO_ID())));
        HttpClientUtil httpClientUtil = new HttpClientUtil();
        JSONObject resJsonData = httpClientUtil.doPost("/taskSys/busi/syf/getCheckTask", token, parms.toString());
        JSONArray obj = resJsonData.getJSONObject("data").getJSONArray("obj");
        if (!obj.isEmpty()) {
            return JSONObject.parseArray(obj.toJSONString(), PageData.class);
        }
//        List<PageData> objDataList = JSONObject.parseArray(obj.toJSONString(), PageData.class);
        return Collections.emptyList();
    }

    // 处理下统一的格式进行上报
    public void initOperation(PageData pageData) {
        pageData.put("deleted", 0);
        pageData.put("createBy", Jurisdiction.getName());
        pageData.put("createDate", DateUtil.date2Str(new Date()));
        pageData.put("updateBy", Jurisdiction.getName());
        pageData.put("updateDate", DateUtil.date2Str(new Date()));
    }

    public void initSaveTable(PageData pageData) {
        pageData.put("creator", "scheduled");
        pageData.put("creatTime", DateUtil.date2Str(new Date()));
        pageData.put("operator", "scheduled");
        pageData.put("operatTime", DateUtil.date2Str(new Date()));
    }

    // 处理查询请求的返回数据
    public static List<PageData> getApiProcessingData(JSONObject resJsonData, Page page, int ty) {
        JSONArray obj = null;
        if (ty == 1) {
            obj = resJsonData.getJSONObject("data").getJSONArray("obj");
        }
        if (ty == 2) {
            obj = resJsonData.getJSONObject("data").getJSONObject("obj").getJSONArray("records");
            List<PageData> objDataList = JSONObject.parseArray(obj.toJSONString(), PageData.class);
            page.setTotalResult(resJsonData.getJSONObject("data").getJSONObject("obj").getInteger("total"));
            List<PageData> collect = objDataList.stream().filter(item -> item.getString("deleted").equals("0")).sorted((o1, o2) -> {
                double checkName1 = Double.parseDouble(o1.getString("checkName"));
                double checkName2 = Double.parseDouble(o2.getString("checkName"));
                return Double.compare(checkName1, checkName2);
            }).collect(Collectors.toList());
            return collect;

        }
        if (ty == 3) {
            obj = resJsonData.getJSONObject("data").getJSONObject("obj").getJSONArray("records");
        }
//        if (ty == 3) {
//            // 评分检查项
//            List<PageData> resData = JSONObject.parseArray("[" + "{\n" + "  \"id\": \"1\",\n" + "  \"companyCode\": \"440000000\",\n" + "  \"taskName\": \"2024 危险化学品危险源企业安全专项检查督导\",\n" + "  \"taskStartTime\": \"2022-11-28\",\n" + "  \"taskEndTime\": \"2023-11-28\",\n" + "  \"taskTypeName\": \"危险化学品重大危险源企业安全专项检查督导\",\n" + "  \"taskContent\": \"危险化学品重大危险源企业2024年专项督查核查\",\n" + "  \"deleted\": \"1\",\n" + "  \"createDate\": \"2020-11-28 11:44:58\",\n" + "  \"updateDate\": \"2020-11-28 11:44:58\"\n" + "}" + ",{\n" + "  \"id\": \"2\",\n" + "  \"companyCode\": \"130110421\",\n" + "  \"taskName\": \"2024 危险化学品危险源企业安全专项检查督导\",\n" + "  \"taskStartTime\": \"2022-11-28\",\n" + "  \"taskEndTime\": \"2023-11-28\",\n" + "  \"taskTypeName\": \"危险化学品重大危险源企业安全专项检查督导\",\n" + "  \"taskContent\": \"危险化学品重大危险源企业2024年专项督查核查\",\n" + "  \"deleted\": \"0\",\n" + "  \"createDate\": \"2021-11-28 11:44:58\",\n" + "  \"updateDate\": \"2021-11-28 11:44:58\"\n" + "}" + ",{\n" + "  \"id\": \"3\",\n" + "  \"companyCode\": \"130110421\",\n" + "  \"taskName\": \"2024 危险化学品危险源企业安全专项检查督导\",\n" + "  \"taskStartTime\": \"2022-11-28\",\n" + "  \"taskEndTime\": \"2023-11-28\",\n" + "  \"taskTypeName\": \"危险化学品重大危险源企业安全专项检查督导\",\n" + "  \"taskContent\": \"危险化学品重大危险源企业2024年专项督查核查\",\n" + "  \"deleted\": \"0\",\n" + "  \"createDate\": \"2022-11-28 11:44:58\",\n" + "  \"updateDate\": \"2022-11-28 11:44:58\"\n" + "}" + ",{\n" + "  \"id\": \"4\",\n" + "  \"companyCode\": \"130110421\",\n" + "  \"taskName\": \"2024 危险化学品危险源企业安全专项检查督导\",\n" + "  \"taskStartTime\": \"2022-11-28\",\n" + "  \"taskEndTime\": \"2023-11-28\",\n" + "  \"taskTypeName\": \"危险化学品重大危险源企业安全专项检查督导\",\n" + "  \"taskContent\": \"危险化学品重大危险源企业2024年专项督查核查\",\n" + "  \"deleted\": \"0\",\n" + "  \"createDate\": \"2023-11-28 11:44:58\",\n" + "  \"updateDate\": \"2023-11-28 11:44:58\"\n" + "}" + "]\n", PageData.class);
////            obj.addAll(resData);
//        }
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<PageData> objDataList = JSONObject.parseArray(obj.toJSONString(), PageData.class);
        // 去掉省平台中 回传被删除数据的值
        List<PageData> collect = objDataList.stream().filter(item -> item.getString("deleted").equals("0")).sorted((o1, o2) -> {
            try {
                Date date1 = dateFormat.parse(o1.getString("createDate"));
                Date date2 = dateFormat.parse(o2.getString("createDate"));
                return date2.compareTo(date1); // 倒排
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }).collect(Collectors.toList());
        List<PageData> paginatedData = getPaginatedData(collect, page.getShowCount(), page.getCurrentPage());
        if (ty == 1 && !paginatedData.isEmpty()) {
            // 设置分页条数
            page.setTotalResult(collect.size());
        }
        return paginatedData;
    }

    public static List<PageData> getPaginatedData(List<PageData> data, int pageSize, int currentPage) {
        if (data == null || data.isEmpty() || pageSize < 0 || currentPage < 0) {
            return new ArrayList<>();
        }

        int totalItems = data.size();
        int totalPages = (int) Math.ceil((double) totalItems / pageSize);

        if (currentPage > totalPages) {
            return new ArrayList<>();
        }
        if (currentPage == 0) currentPage = 1;
        int startIndex = (currentPage - 1) * pageSize;
        int endIndex = Math.min(startIndex + pageSize, totalItems);

        return new ArrayList<>(data.subList(startIndex, endIndex));
    }

    public static String getProvincialPaginated(PageData ftParms) {
        JSONObject pageParm = new JSONObject();
        pageParm.put("current", Integer.parseInt(ftParms.getString("currentPage")));
        pageParm.put("size", Integer.parseInt(ftParms.getString("showCount")));
        return pageParm.toJSONString();
    }

    // 处理批处理结果数据 需要 转码

    public static void main(String[] args) {


        String logtorecord = logtorecord();
        System.out.println("------------------------------------------------------------");
        logHiddenRecord(logtorecord);
    }

    private static void logHiddenRecord(String id) {
        System.out.println(id);
        Map<String, Object> data = new HashMap<>();
        // 手动将 JSON 对象中的每个键值对添加到 Map 中
        String dangerId = UUID.randomUUID().toString();

        data.put("id", dangerId);
        data.put("com2panyCode", "130110421");
        data.put("dangerId", id);
        data.put("taskId", "d95a3933-ad2e-4586-bd7d-21056306e781");
        data.put("checkType", "3");
        data.put("checkItemId", "3552f08a-9558-42ab-9349-01b880b0af6b");
        data.put("checkScoreId", "87acf414-7d29-464b-a9a0-23cc3c46a0a7");
        data.put("checkDate", "2024-05-30");
        data.put("checkPay", "0");
        data.put("harmType", "1");

        data.put("updateDate", "2024-05-30 10:17:25");
        data.put("updateBy", "卓云企业");
        data.put("createDate", "2024-05-30 10:17:25");
        data.put("createBy", "卓云企业");
        data.put("deleted", "0");
        JSONArray waitFreportRecordHidden = new JSONArray();
        waitFreportRecordHidden.add(data);
        System.out.println(waitFreportRecordHidden);
        String encryptHidden = AesGcm256Util.encrypt(waitFreportRecordHidden.toString(), AesGcm256Util.hexToByte(ConstCorps.KEY), AesGcm256Util.hexToByte(ConstCorps.IV));
        System.out.println(encryptHidden);
        String encryptHidden2 = AesGcm256Util.decrypt(encryptHidden, AesGcm256Util.hexToByte(ConstCorps.KEY), AesGcm256Util.hexToByte(ConstCorps.IV));
        System.out.println(encryptHidden2);
    }

    private static String logtorecord() {
        Map<String, Object> data = new HashMap<>();
        String dangerId = UUID.randomUUID().toString();
        System.out.println(dangerId);

        // 手动将 JSON 对象中的每个键值对添加到 Map 中
        data.put("id", dangerId);
        data.put("taskId", "d95a3933-ad2e-4586-bd7d-21056306e781");
        data.put("hazardCode", "130110421001");
        data.put("companyCode", "130110421");
        data.put("checkType", "3");
        data.put("checkDate", "2023-05-15");
        data.put("resultStatus", "0");

        data.put("createDate", "2024-05-30 10:17:25");
        data.put("createBy", "卓云企业");
        data.put("deleted", "0");
        data.put("updateDate", "2024-05-30 10:17:25");
        data.put("updateBy", "卓云企业");

        JSONArray waitFreportRecordHidden = new JSONArray();
        waitFreportRecordHidden.add(data);
        System.out.println(waitFreportRecordHidden);
        String encryptHidden = AesGcm256Util.encrypt(waitFreportRecordHidden.toString(), AesGcm256Util.hexToByte(ConstCorps.KEY), AesGcm256Util.hexToByte(ConstCorps.IV));
        System.out.println(encryptHidden);
        String encryptHidden2 = AesGcm256Util.decrypt(encryptHidden, AesGcm256Util.hexToByte(ConstCorps.KEY), AesGcm256Util.hexToByte(ConstCorps.IV));
        System.out.println(encryptHidden2);
        return dangerId;
    }
}
