package com.bcxin.ferry.service;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bcxin.ferry.common.emus.SendBoundaryUrlEnum;
import com.bcxin.ferry.common.utils.IdGeneratorSnowflake;
import com.bcxin.ferry.dao.mapper.FerryErrorInfoMapper;
import com.bcxin.ferry.entity.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 摆渡异常信息表(ferry_error_info)服务实现类
 *
 * @author : linchunpeng
 * @date : 2024-3-6
 */
@Slf4j
@Service
public class FerryErrorInfoService extends ServiceImpl<FerryErrorInfoMapper, FerryErrorInfoEntity> {

    @Autowired
    private FerryTaskService ferryTaskService;
    @Autowired
    private FerryTaskFileService ferryTaskFileService;
    @Autowired
    private FerryReceiveTaskService ferryReceiveTaskService;
    @Autowired
    private FerryReceiveTaskFileService ferryReceiveTaskFileService;
    @Autowired
    private IdGeneratorSnowflake snowflake;


    /**
     * description：扫描异常信息
     * author：linchunpeng
     * date：2024/3/20
     */
    public void scanErrorInfo() {
        log.info("扫描异常信息:1、是否有大于一小时还未摆渡完成的任务？");
        List<FerryErrorInfoEntity> insertList = new ArrayList<>();
        //1、是否有大于一小时还未摆渡完成的任务？
        List<FerryTaskEntity> notCompleteFerryTaskList = ferryTaskService.queryOneHourNotCompleteList();
        if (CollectionUtil.isNotEmpty(notCompleteFerryTaskList)) {
            for (FerryTaskEntity ferryTaskEntity : notCompleteFerryTaskList) {
                log.info("扫描异常信息:1、有");
                insertList.add(this.createFerryErrorInfoEntity(ferryTaskEntity.getId(), null, null,
                        null, "摆渡任务大于一个小时还未摆渡完成"));
            }
        }
        log.info("扫描异常信息:2、上个任务完成时间是否大于一个半小时还未生成新任务（暂时去掉）");
        //2、上个任务完成时间是否大于一个半小时还未生成新任务
//        if (ferryTaskService.isNotCreateNewTask()) {
//            log.info("扫描异常信息:2、有");
//            insertList.add(this.createFerryErrorInfoEntity(null, null, null,
//                    null, "上个摆渡任务完成时间大于一个半小时还未生成新任务", ""));
//        }
        log.info("扫描异常信息:3、是否有大于半小时还未摆渡完成的文件？");
        //3、是否有大于半小时还未摆渡完成的文件？
        List<FerryTaskFileEntity> notCompleteFerryFileList = ferryTaskFileService.queryHalfHourNotCompleteList();
        if (CollectionUtil.isNotEmpty(notCompleteFerryFileList)) {
            log.info("扫描异常信息:3、有");
            for (FerryTaskFileEntity fileEntity : notCompleteFerryFileList) {
                log.info("扫描异常信息:文件id：{}，大于半小时还未摆渡完成，进行重试", fileEntity.getId());
                if (fileEntity.getRetryCount() == null || fileEntity.getRetryCount() < 10) {
                    log.info("扫描异常信息:文件id：{}，重试次数：{}", fileEntity.getId(), fileEntity.getRetryCount() == null ? 1 : fileEntity.getRetryCount() + 1);
                    //摆渡重试
                    ferryTaskFileService.ferryFileToBoundary(fileEntity, SendBoundaryUrlEnum.SEND_DETAIL_FILE);
                } else {
                    log.info("扫描异常信息:文件id：{}，重试次数：{}，已达最大重试次数，记录记录，不再重试", fileEntity.getId(), fileEntity.getRetryCount() == null ? 1 : fileEntity.getRetryCount() + 1);
                    insertList.add(this.createFerryErrorInfoEntity(fileEntity.getTaskId(), fileEntity.getId(), null,
                            null, "摆渡文件大于一个小时还未摆渡完成"));
                }
            }
        }
        log.info("扫描异常信息:4、是否有接收任务大于一个小时还未摆渡完成的任务？");
        //4、是否有接收任务大于一个小时还未摆渡完成的任务？
        List<FerryReceiveTaskEntity> notCompleteReceiveTaskList = ferryReceiveTaskService.queryOneHourNotCompleteList();
        if (CollectionUtil.isNotEmpty(notCompleteReceiveTaskList)) {
            log.info("扫描异常信息:4、有");
            for (FerryReceiveTaskEntity receiveTaskEntity : notCompleteReceiveTaskList) {
                insertList.add(this.createFerryErrorInfoEntity(receiveTaskEntity.getFerryTaskId(), null, receiveTaskEntity.getId(),
                        null, "接收任务大于一个小时还未摆渡完成"));
            }
        }
        log.info("扫描异常信息:5、是否有上个接收任务完成时间大于一个半小x时还未生成新任务？");
        //5、是否有上个接收任务完成时间大于一个半小时还未生成新任务
        if (ferryReceiveTaskService.isNotCreateNewTask()) {
            log.info("扫描异常信息:5、有");
            insertList.add(this.createFerryErrorInfoEntity(null, null, null,
                    null, "上个接收任务完成时间大于一个半小时还未生成新任务"));
        }
        log.info("扫描异常信息:6、是否接收文件大于一个小时还未摆渡完成？（暂时去掉）");
        //6、是否接收文件大于一个小时还未摆渡完成？
//        List<FerryReceiveTaskFileEntity> notCompleteReceiveFileList = ferryReceiveTaskFileService.queryHalfHourNotCompleteList();
//        if (CollectionUtil.isNotEmpty(notCompleteReceiveFileList)) {
//            log.info("扫描异常信息:6、有？");
//            for (FerryReceiveTaskFileEntity fileEntity : notCompleteReceiveFileList) {
//                insertList.add(this.createFerryErrorInfoEntity(null, null, fileEntity.getTaskId(),
//                        fileEntity.getId(), "接收文件大于一个小时还未摆渡完成", JSONObject.toJSONString(fileEntity)));
//            }
//        }
        if (CollectionUtil.isNotEmpty(insertList)) {
            this.saveBatch(insertList);
        }
    }

    /**
     * description：创建异常记录
     * author：linchunpeng
     * date：2024/3/20
     */
    private FerryErrorInfoEntity createFerryErrorInfoEntity(Long ferryTaskId, Long ferryFileId, Long receiveTaskId,
                                                            Long receiveFileId, String errorMessage) {
        FerryErrorInfoEntity entity = new FerryErrorInfoEntity();
        entity.setId(snowflake.snowflakeId());
        entity.setFerryTaskId(ferryTaskId);
        entity.setFerryFileId(ferryFileId);
        entity.setReceiveTaskId(receiveTaskId);
        entity.setReceiveFileId(receiveFileId);
        entity.setErrorMessage(errorMessage);
        entity.setHandleStatus(1);
        entity.setCreateTime(new Date());
        entity.setUpdateTime(new Date());
        return entity;
    }
}