package com.wms_main.service.quartz_job.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wms_main.app.AppCommon;
import com.wms_main.constant.enums.others.DbsStatusEnums;
import com.wms_main.constant.enums.wms.AppConfigKeyEnums;
import com.wms_main.dao.*;
import com.wms_main.excel.easypoi.service.ISaveExcelEasyPoi;
import com.wms_main.model.po.*;
import com.wms_main.service.quartz_job.IDataSolverService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 数据处理类 服务实现
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class DataSolverServiceImpl implements IDataSolverService {
    private final AppCommon appCommon;// 应用共同数据
    private final ITSysApiService sysApiService;// 接口发送日志服务
    private final ITSysLogService sysLogService;// 接口接收日志服务
    private final ITAppTaskBakService appTaskBakService;// Wms任务记录服务
    private final ITAppWcsTaskBakService appWcsTaskBakService;// Wcs任务记录服务
    private final ITAppPickTaskBakService appPickTaskBakService;// 拣选任务记录服务
    private final ISaveExcelEasyPoi saveExcelEasyPoi;// 记录保存excel服务
    private final ITAppStockUpdateService appStockUpdateService;// 库存流水服务
    private final ITAppInventoryRecordService appInventoryRecordService;// 盘点记录服务
    private final ITAppOutsRecordService appOutsRecordService;// 出库单记录服务
    private final ITAppWorkRecordService appWorkRecordService;// 工作记录服务
    private final ITAppDbsService appDbsService;// Dbs服务

    /**
     * 清理日志文件 实现
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void clearLogData() {
        // 日志清理间隔，默认7天
        int logClearInterval = 7;
        // 获取日志清理间隔
        String logClearIntervalStr = appCommon.getConfigByKey(AppConfigKeyEnums.LOG_CLEAR_INTERVAL.getKey());
        try {
            logClearInterval = Integer.parseInt(logClearIntervalStr);
        } catch (Exception e) {
            log.warn("获取日志清理间隔失败，使用默认值7天。");
        }
        // 获取删除时间
        LocalDateTime deleteTime = LocalDateTime.now().minusDays(logClearInterval);

        // 获取过期接口接收日志
        List<TSysLog> logList = sysLogService.list(new LambdaQueryWrapper<TSysLog>().lt(TSysLog::getLogTime, deleteTime));
        if (logList != null && !logList.isEmpty()) {
            // 缓存接收记录
            saveExcelEasyPoi.saveApiReceiveLogs(getSuffixFromDate(deleteTime, logClearInterval), logList);
            // 删除接收记录
            sysLogService.removeBatchByIds(logList);
            log.info("清理日志文件成功，清理了{}条接口接收日志。", logList.size());
        }

        // 获取过期接口发送日志
        List<TSysApi> apiList = sysApiService.list(new LambdaQueryWrapper<TSysApi>().lt(TSysApi::getLogTime, deleteTime));
        if (apiList != null && !apiList.isEmpty()) {
            // 缓存发送记录
            saveExcelEasyPoi.saveApiSendLogs(getSuffixFromDate(deleteTime, logClearInterval), apiList);
            // 删除发送记录
            sysApiService.removeBatchByIds(apiList);
            log.info("清理日志文件成功，清理了{}条接口发送日志。", apiList.size());
        }
    }

    /**
     * 清理普通记录文件 实现
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void clearNormalRecord() {
        // 普通记录清理间隔，默认180天
        int normalRecordClearInterval = 180;
        // 获取普通记录清理间隔
        String normalRecordClearIntervalStr = appCommon.getConfigByKey(AppConfigKeyEnums.NORMAL_DATA_CLEAR_INTERVAL.getKey());
        try {
            normalRecordClearInterval = Integer.parseInt(normalRecordClearIntervalStr);
        } catch (Exception e) {
            log.warn("获取普通记录清理间隔失败，使用默认值180天。");
        }
        // 获取删除时间
        LocalDateTime deleteTime = LocalDateTime.now().minusDays(normalRecordClearInterval);

        // 查询Wms任务记录
        List<TAppTaskBak> wmsTaskBakList = appTaskBakService.list(new LambdaQueryWrapper<TAppTaskBak>().lt(TAppTaskBak::getCreateTime, deleteTime));
        if (wmsTaskBakList != null && !wmsTaskBakList.isEmpty()) {
            // 备份数据
            saveExcelEasyPoi.saveWmsTaskBak(getSuffixFromDate(deleteTime, normalRecordClearInterval), wmsTaskBakList);
            // 删除记录
            appTaskBakService.removeBatchByIds(wmsTaskBakList);
            log.info("清理普通记录文件成功，清理了{}条Wms任务记录。", wmsTaskBakList.size());
        }
        // 查询Wcs任务记录
        List<TAppWcsTaskBak> wcsTaskBakList = appWcsTaskBakService.list(new LambdaQueryWrapper<TAppWcsTaskBak>().lt(TAppWcsTaskBak::getCreateTime, deleteTime));
        if (wcsTaskBakList != null && !wcsTaskBakList.isEmpty()) {
            // 备份数据
            saveExcelEasyPoi.saveWcsTaskBak(getSuffixFromDate(deleteTime, normalRecordClearInterval), wcsTaskBakList);
            // 删除记录
            appWcsTaskBakService.removeBatchByIds(wcsTaskBakList);
            log.info("清理普通记录文件成功，清理了{}条Wcs任务记录。", wcsTaskBakList.size());
        }
        // 查询拣选任务记录
        List<TAppPickTaskBak> pickTaskBakList = appPickTaskBakService.list(new LambdaQueryWrapper<TAppPickTaskBak>().lt(TAppPickTaskBak::getCreateTime, deleteTime));
        if (pickTaskBakList != null && !pickTaskBakList.isEmpty()) {
            // 备份数据
            saveExcelEasyPoi.savePickTaskBak(getSuffixFromDate(deleteTime, normalRecordClearInterval), pickTaskBakList);
            // 删除记录
            appPickTaskBakService.removeBatchByIds(pickTaskBakList);
            log.info("清理普通记录文件成功，清理了{}条拣选任务记录。", pickTaskBakList.size());
        }
    }

    /**
     * 清理重要记录文件 实现
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void clearImportantRecord() {
        // 重要记录清理间隔，默认365天
        int importantRecordClearInterval = 365;
        // 获取重要记录清理间隔
        String importantRecordClearIntervalStr = appCommon.getConfigByKey(AppConfigKeyEnums.IMPORTANT_DATA_CLEAR_INTERVAL.getKey());
        try {
            importantRecordClearInterval = Integer.parseInt(importantRecordClearIntervalStr);
        } catch (Exception e) {
            log.warn("获取重要记录清理间隔失败，使用默认值365天。");
        }
        // 获取删除时间
        LocalDateTime deleteTime = LocalDateTime.now().minusDays(importantRecordClearInterval);

        // 查询过期库存流水记录
        List<TAppStockUpdate> stockUpdateList = appStockUpdateService.list(new LambdaQueryWrapper<TAppStockUpdate>().lt(TAppStockUpdate::getUpdateTime, deleteTime));
        if (stockUpdateList != null && !stockUpdateList.isEmpty()) {
            // 备份过期数据
            saveExcelEasyPoi.saveStockUpdateRecord(getSuffixFromDate(deleteTime, importantRecordClearInterval), stockUpdateList);
            // 清理过期数据
            appStockUpdateService.removeBatchByIds(stockUpdateList);
        }
        // 查询过期盘点记录
        List<TAppInventoryRecord> inventoryRecordList = appInventoryRecordService.list(new LambdaQueryWrapper<TAppInventoryRecord>().lt(TAppInventoryRecord::getInvConfirmTime, deleteTime));
        if (inventoryRecordList != null && !inventoryRecordList.isEmpty()) {
            // 缓存过期数据
            saveExcelEasyPoi.saveInventoryRecord(getSuffixFromDate(deleteTime, importantRecordClearInterval), inventoryRecordList);
            // 删除过期数据
            appInventoryRecordService.removeBatchByIds(inventoryRecordList);
        }
        // 查询过期出库单请求记录
        List<TAppOutsRecord> outsRecordList = appOutsRecordService.list(new LambdaQueryWrapper<TAppOutsRecord>().lt(TAppOutsRecord::getRequestTime, deleteTime));
        if (outsRecordList != null && !outsRecordList.isEmpty()) {
            // 缓存过期数据
            saveExcelEasyPoi.saveOutsRecord(getSuffixFromDate(deleteTime, importantRecordClearInterval), outsRecordList);
            // 删除过期数据
            appOutsRecordService.removeBatchByIds(outsRecordList);
        }
        // 查询过期工作记录
        List<TAppWorkRecord> workRecordList = appWorkRecordService.list(new LambdaQueryWrapper<TAppWorkRecord>().lt(TAppWorkRecord::getFinishTime, deleteTime));
        if (workRecordList != null && !workRecordList.isEmpty()) {
            // 缓存过期数据
            saveExcelEasyPoi.saveWorkRecord(getSuffixFromDate(deleteTime, importantRecordClearInterval), workRecordList);
            // 删除过期数据
            appWorkRecordService.removeBatchByIds(workRecordList);
        }
        // 查询过期dbs数据
        List<TAppDbs> dbsRecordList = appDbsService.list(new LambdaQueryWrapper<TAppDbs>().lt(TAppDbs::getFinishTime, deleteTime).eq(TAppDbs::getDbsStatus, DbsStatusEnums.FINISH.getValue()));
        if (dbsRecordList != null && !dbsRecordList.isEmpty()) {
            // 缓存过期数据
            saveExcelEasyPoi.saveDbsRecord(getSuffixFromDate(deleteTime, importantRecordClearInterval), dbsRecordList);
            // 删除过期数据
            appDbsService.removeBatchByIds(dbsRecordList);
        }
    }

    /**
     * 获取到文件的时间后缀
     * @param deleteTime 删除临界时间
     * @return 后缀字符串
     */
    private String getSuffixFromDate(LocalDateTime deleteTime, int clearInterval) {
        DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyyMMdd");
        String fromDateStr = dateFormat.format(deleteTime.minusDays(clearInterval));
        String toDateStr = dateFormat.format(deleteTime);
        return fromDateStr + "~" + toDateStr;
    }
}
