package com.njcn.influx.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.njcn.influx.bo.po.*;
import com.njcn.influx.mapper.OracleRmpEventDetailPOMapper;
import com.njcn.influx.mapper.PqDeviceMapper;
import com.njcn.influx.mapper.RmpEventDetailPOMapper;
import com.njcn.influx.service.OracleToMysqlService;
import com.njcn.influx.service.PqLineBakService;
import com.njcn.influx.service.PqsEventLogService;
import com.njcn.influx.service.RmpEventDetailService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Description:
 * Date: 2026/04/20  上午 9:54【需求编号】
 *
 * @author clam
 * @version V1.0.0
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class OracleToMysqlServiceImpl implements OracleToMysqlService {

    private final RmpEventDetailService rmpEventDetailService;
    private final OracleRmpEventDetailPOMapper oracleRmpEventDetailPOMapper;


    private final PqsEventLogService pqsEventLogService;
    private final EventAsyncService eventAsyncService;
    @Value("${business.dealFlag:true}")
    private Boolean dealFlag;
    @Value("${business.upLoadFlag:true}")
    private Boolean upLoadFlag;
    @Override
    public void OracleToMySqlJob(LocalDateTime start, LocalDateTime end) {
        log.info("===== 定时扫描事件开始 =====");

        List<OracleRmpEventDetailPO> oracleRmpEventDetailPOList = oracleRmpEventDetailPOMapper.selectList(new LambdaQueryWrapper<OracleRmpEventDetailPO>().between(OracleRmpEventDetailPO::getCreateTime,start,end));
        for (OracleRmpEventDetailPO detail : oracleRmpEventDetailPOList) {
            String eventId = detail.getEventId();

            // 2. 判断是否已存在日志，避免重复
            Integer cnt = pqsEventLogService.lambdaQuery().eq(PqsEventLog::getEventdetailIndex,eventId).count();

            if (cnt == null ||cnt < 1){
                // 3. 初始化日志：0未上传 0未计算
                PqsEventLog pqsEventLog = new PqsEventLog();
                pqsEventLog.setId(UUID.randomUUID().toString());
                pqsEventLog.setEventdetailIndex(eventId);
                //判断是否配置数据同步或者高级算法功能
                if(dealFlag){
                    pqsEventLog.setDealflag(0);
                }else {
                    pqsEventLog.setDealflag(2);
                }
                if(dealFlag){
                    pqsEventLog.setFileupflag(0);
                }else {
                    pqsEventLog.setFileupflag(2);
                }

                pqsEventLog.setFileupflag(0);
                pqsEventLog.setCreattime(new Date());
                pqsEventLog.setUpdatetime(new Date());
                pqsEventLogService.save(pqsEventLog);

                String wavename = detail.getWavePath();

                rmpEventDetailService.syncToMysql(eventId);

                // ============================
                // WAVENAME 为空：直接标记
                // ============================
                if (wavename == null || wavename.trim().isEmpty()) {

                    continue;
                }

                // ============================
                // WAVENAME 非空：线程池异步处理
                // ============================
                eventAsyncService.asyncHandleEvent(detail);
            }


        }
    }

    @Override
    public void retryAndCleanEvery10Min() {
        log.info("===== 10分钟重试补偿 + 过期清理 =====");

        // 1. 扫描未处理：fileup=0 deal=0
        List<PqsEventLog> todoList = pqsEventLogService.lambdaQuery().eq(PqsEventLog::getFileupflag, 0)
                .or()
                .eq(PqsEventLog::getDealflag, 0).list();

        for (PqsEventLog log : todoList) {
            String eventId = log.getEventdetailIndex();
            Date createTime = log.getCreattime();
            OracleRmpEventDetailPO oracleRmpEventDetailPO = oracleRmpEventDetailPOMapper.selectById(eventId);
            // 查询最新WAVENAME


            boolean isWaveEmpty = (oracleRmpEventDetailPO.getWavePath() == null || oracleRmpEventDetailPO.getWavePath().isEmpty());

            // ======================
            // 超过2天：置为2
            // ======================
            if (createTime != null && System.currentTimeMillis() - createTime.getTime() > 2 * 86400000L) {
                if (isWaveEmpty) {
                    pqsEventLogService.lambdaUpdate().set(PqsEventLog::getDealflag,2).set(PqsEventLog::getFileupflag,2).set(PqsEventLog::getUpdatetime,new Date()).eq(PqsEventLog::getEventdetailIndex,eventId).update();
                    continue;
                }
            }

            // ======================
            // 有文件：重试异步处理
            // ======================
            if (!isWaveEmpty) {
                eventAsyncService.asyncHandleEvent(oracleRmpEventDetailPO);
            }
        }

    }

}
