package com.ningdatech.pmapi.projectlib.handle;


import java.util.List;
import com.ningdatech.pmapi.projectlib.model.entity.Project;
import com.ningdatech.pmapi.projectlib.service.IProjectService;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ningdatech.pmapi.common.constant.CommonConst;
import com.ningdatech.pmapi.common.statemachine.event.ProjectStatusChangeEvent;
import com.ningdatech.pmapi.projectlib.enumeration.ProjectStatusEnum;
import com.ningdatech.pmapi.projectlib.enumeration.StepStatusEnum;
import com.ningdatech.pmapi.projectlib.model.entity.ProjectStatusChange;
import com.ningdatech.pmapi.projectlib.model.vo.ProcessDetailVO;
import com.ningdatech.pmapi.projectlib.service.INdProjectStatusChangeService;

/**
 * 归档处理
 *
 * @author CMM
 * @since 2023/02/24 14:35
 */
@Order(11)
@Component
public class ArchivedHandle extends AbstractProcessBusinessHandle {
    private final IProjectService projectService;
    private final INdProjectStatusChangeService projectStatusChangeService;

    public ArchivedHandle( IProjectService projectService, INdProjectStatusChangeService projectStatusChangeService){
        this.projectService = projectService;
        this.projectStatusChangeService = projectStatusChangeService;
    }

    @Override
    void businessHandle(Long projectId, List<ProcessDetailVO> processSchedule) {
        ProcessDetailVO processDetailVO = new ProcessDetailVO();
        Project project = projectService.getById(projectId);
        Integer status = project.getStage();
        // 根据项目阶段判断是否已归档
        // 项目阶段不为已归档
        if (!ProjectStatusEnum.ARCHIVED.getCode().equals(status)){
            processDetailVO.setStepStatus(StepStatusEnum.NOT_START);
            processDetailVO.setProcessName(CommonConst.ARCHIVED);
            processSchedule.add(processDetailVO);
            return;
        }
        // 项目阶段为已归档
        processDetailVO.setStepStatus(StepStatusEnum.COMPLETED);
        // 根据项目终验获取归档时间
        ProjectStatusChange projectStatusChange = projectStatusChangeService.getOne(Wrappers.lambdaQuery(ProjectStatusChange.class)
                .eq(ProjectStatusChange::getProjectId, projectId)
                .eq(ProjectStatusChange::getEvent, ProjectStatusChangeEvent.FINAL_ACCEPTANCE_PASS.name())
                .last("limit 1"));
        processDetailVO.setFinishTime(projectStatusChange.getCreateOn());
        processDetailVO.setProcessName(CommonConst.ARCHIVED);
        processSchedule.add(processDetailVO);
    }
}
