package cn.stylefeng.workflow.instance.core.condition;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.stylefeng.workflow.api.enums.ApproverTypeEnum;
import cn.stylefeng.workflow.api.pojo.InstanceContext;
import cn.stylefeng.workflow.api.pojo.config.node.approver.ApproverConfig;
import cn.stylefeng.workflow.api.pojo.config.node.approver.ApproverSummary;
import cn.stylefeng.workflow.instance.core.condition.base.BaseApproverRule;
import cn.stylefeng.workflow.instance.core.condition.holder.SubmitterUserIdHolder;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SubmitterApproverRule extends BaseApproverRule {

    @Override
    public boolean approverEvaluate(InstanceContext instanceContext, ApproverConfig approverConfig) {
        ApproverSummary mainApprover = approverConfig.getMainApprover();
        if (ObjectUtil.isEmpty(mainApprover)) {
            return false;
        }

        if (!ApproverTypeEnum.SUBMITTER_SELF.getValue().equals(mainApprover.getApproverType())) {
            return false;
        }

        Boolean submitterSelfFlag = mainApprover.getSubmitterSelfFlag();
        if (ObjectUtil.isEmpty(submitterSelfFlag)) {
            return false;
        }

        return submitterSelfFlag;
    }

    @Override
    public void approverExecute(InstanceContext instanceContext, ApproverConfig approverConfig) {

        Long submitter = SubmitterUserIdHolder.getSubmitter();
        if (submitter != null) {
            setResult(ListUtil.of(submitter));
            return;
        }

        Long applicant = instanceContext.getRuntimeInstance().getApplicant();
        setResult(ListUtil.of(applicant));
    }

    @Override
    public String getBaseRuleName() {
        return SubmitterApproverRule.class.getName();
    }

    @Override
    public int getBaseRulePriority() {
        return 700;
    }

}




