package com.ningdatech.pmapi.staging.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ningdatech.pmapi.projectlib.model.entity.Project;
import com.ningdatech.pmapi.staging.contants.StagingContant;
import com.ningdatech.pmapi.staging.mapper.ProjectStagingMapper;
import com.ningdatech.pmapi.staging.model.entity.ProjectStaging;
import com.ningdatech.pmapi.staging.service.IProjectStagingService;
import com.ningdatech.pmapi.staging.utils.ProjectStatusFlowMapUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zpf
 * @since 2023-02-18
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class ProjectStagingServiceImpl extends ServiceImpl<ProjectStagingMapper, ProjectStaging> implements IProjectStagingService {

    private final ProjectStagingMapper mapper;

    private final ProjectStatusFlowMapUtil projectStatusFlowMapUtil;

    /**
     * 在某些状态节点 增加一个项目到状态暂存库
     * @param project
     * @return
     */
    @Override
    public Boolean addByProject(Project project,String remark) {
        ProjectStaging projectStaging = ProjectStaging.builder()
                .projectId(project.getId())
                .projectName(project.getProjectName())
                .stage(project.getStage())
                .status(project.getStatus())
                .createOn(LocalDateTime.now())
                .updateOn(LocalDateTime.now())
                .instCode(project.getInstCode())
                .processStatus(project.getProcessStatus())
                .nextTime(LocalDateTime.now())
                .retryTimes(0)
                .remark(remark)
                .build();
        return this.save(projectStaging);
    }

    /**
     * 增加 重试次数 和下次扫描时间
     * @param projectStaging
     * @return
     */
    @Override
    public Boolean addRetryTimes(ProjectStaging projectStaging) {
        Integer retryTimes = projectStaging.getRetryTimes() + 1;
        if(!projectStatusFlowMapUtil.intervalTimeMap.containsKey(retryTimes)){
            log.info("没有对应重试间隔时间 添加重试信息失败");
            return Boolean.FALSE;
        }
        Integer addSeconds = projectStatusFlowMapUtil.intervalTimeMap.get(retryTimes);
        Boolean dead = Boolean.FALSE;
        //超过重试最大次数 dead置为 true
        if(retryTimes.compareTo(StagingContant.Retry.MAX_RETRY_TIMES) > 0){
            dead = Boolean.TRUE;
        }
        LocalDateTime nextRetryTime = LocalDateTime.now().plusSeconds(addSeconds);
        return mapper.addRetryTimes(projectStaging.getId(),retryTimes,nextRetryTime,dead);
    }
}
