package cn.stylefeng.workflow.instance.modular.task.strategy.emptyprocess;

import cn.hutool.core.util.ObjectUtil;
import cn.stylefeng.roses.kernel.sys.api.OrgApproverServiceApi;
import cn.stylefeng.roses.kernel.sys.api.enums.org.DetectModeEnum;
import cn.stylefeng.roses.kernel.sys.api.enums.org.OrgApproverTypeEnum;
import cn.stylefeng.workflow.api.entity.design.Node;
import cn.stylefeng.workflow.api.entity.instance.RuntimeNode;
import cn.stylefeng.workflow.api.enums.TaskTypeEnum;
import cn.stylefeng.workflow.api.enums.strategy.EmptyApproverStrategyEnum;
import cn.stylefeng.workflow.api.pojo.InstanceContext;
import cn.stylefeng.workflow.instance.modular.task.service.RuTaskService;
import cn.stylefeng.workflow.instance.modular.task.strategy.emptyprocess.base.EmptyApproverRule;
import cn.stylefeng.workflow.log.api.WorkflowLogApi;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
public class LeaderReplaceRule implements EmptyApproverRule {

    @Resource
    private RuTaskService ruTaskService;

    @Resource
    private WorkflowLogApi workflowLogApi;

    @Resource
    private OrgApproverServiceApi orgApproverServiceApi;

    @Override
    public EmptyApproverStrategyEnum getStrategyType() {
        return EmptyApproverStrategyEnum.LEADER;
    }

    @Override
    public void processEmptyApprover(Node currentNode, InstanceContext instanceContext, RuntimeNode runtimeNode) {

        Long userOrgId = instanceContext.getRuntimeInstance().getApplicantOrgId();

        List<Long> userMainOrgApprover = orgApproverServiceApi.getDeptOrgApprover(userOrgId, OrgApproverTypeEnum.FZR.getCode(), 0, DetectModeEnum.TO_TOP);

        if (ObjectUtil.isEmpty(userMainOrgApprover)) {
            workflowLogApi.logFail(instanceContext, currentNode.getNodeId(), "执行审批策略-审批人为空时，由上级主管代替审批失败，上级主管为空");
            return;
        }

        ruTaskService.createUserTask(userMainOrgApprover.get(0), TaskTypeEnum.PROCESSING, runtimeNode, instanceContext);

        workflowLogApi.logSuccess(instanceContext, currentNode.getNodeId(), "执行审批策略-审批人为空时，由上级主管代替审批");

    }

}
