package com.ningdatech.pmapi.common.statemachine.factory;

import cn.hutool.core.collection.CollUtil;
import com.ningdatech.pmapi.common.constant.ProjectDeclareConst;
import com.ningdatech.pmapi.common.constant.StateMachineConst;
import com.ningdatech.pmapi.common.enumeration.CommonEnum;
import com.ningdatech.pmapi.common.statemachine.util.StateMachineUtils;
import com.ningdatech.pmapi.common.statemachine.event.ProjectStatusChangeEvent;
import com.ningdatech.pmapi.projectlib.enumeration.ProjectStatusEnum;
import com.ningdatech.pmapi.projectlib.model.entity.Project;
import com.ningdatech.pmapi.projectlib.model.entity.ProjectApplication;
import org.springframework.statemachine.StateContext;
import org.springframework.statemachine.guard.Guard;

import java.util.List;

import static com.ningdatech.pmapi.common.constant.StateMachineConst.APPLICATION_DECLARE;

/**
 * 项目申报状态机guard集合类
 *
 * @author CMM
 * @since 2023/02/07 16:18
 */

public class ProjectDeclareGuardFactory {
    private static final String PROJECT_DECLARE = StateMachineConst.PROJECT_DECLARE;

    public class PendingPreQualificationChoiceGuard implements Guard<ProjectStatusEnum, ProjectStatusChangeEvent> {
        @Override
        public boolean evaluate(StateContext<ProjectStatusEnum, ProjectStatusChangeEvent> context) {
            Project project = context.getMessage().getHeaders().get(PROJECT_DECLARE, Project.class);
            // 判断申报项目是否是市级项目，且申报金额是否大于等于1000万元
            if (StateMachineUtils.isCityProject(project) && StateMachineUtils.judgeDeclareAmount(project,
                    ProjectDeclareConst.Number.DECLARE_AMOUNT_JUDGEMENT)){
                return true;
            }
            return false;
        }
    }

    public class ApprovedAfterChoiceGuard implements Guard<ProjectStatusEnum, ProjectStatusChangeEvent> {
        @Override
        public boolean evaluate(StateContext<ProjectStatusEnum, ProjectStatusChangeEvent> context) {
            List<ProjectApplication> projectApplications = context.getMessage().getHeaders().get(APPLICATION_DECLARE, List.class);
            final Boolean[] res = {Boolean.FALSE};
            // 判断 是否有初次创建的应用
            if (CollUtil.isEmpty(projectApplications)){
                return res[0];
            }
            projectApplications.stream().forEach(app -> {
                Integer isFirst = app.getIsFirst();
                if(isFirst.equals(CommonEnum.YES.getCode())){
                    res[0] =  Boolean.TRUE;
                }
            });
            return res[0];
        }
    }
}
