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

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.api.pojo.config.node.approver.detail.NodeApproverCustom;
import cn.stylefeng.workflow.api.rule.BaseCustomApproverRule;
import cn.stylefeng.workflow.instance.core.condition.base.BaseApproverRule;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class CustomApproverRule extends BaseApproverRule {

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

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

        NodeApproverCustom nodeApproverCustom = mainApprover.getNodeApproverCustom();
        if (ObjectUtil.isEmpty(nodeApproverCustom)) {
            return false;
        }

        if (ObjectUtil.isEmpty(nodeApproverCustom.getCustomExpandRuleClass())) {
            return false;
        }

        return true;
    }

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

        NodeApproverCustom nodeApproverCustom = approverConfig.getMainApprover().getNodeApproverCustom();
        String customExpandRuleClass = nodeApproverCustom.getCustomExpandRuleClass();

        Class<?> pointClass = null;
        try {
            pointClass = Class.forName(customExpandRuleClass);
        } catch (ClassNotFoundException e) {
            log.error("基于自定义规则查找人员信息，无法创建自定义类，类名为：{}", customExpandRuleClass);
            return;
        }

        try {
            BaseCustomApproverRule baseAgreeStrategy = (BaseCustomApproverRule) pointClass.newInstance();
            List<Long> userIdList = baseAgreeStrategy.determineApprover(instanceContext);
            setResult(new ArrayList<>(userIdList));
        } catch (InstantiationException | IllegalAccessException e) {
            log.error("基于自定义规则查找人员信息，实例化自定义类失败，类名为：{}", customExpandRuleClass);
        }

    }

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

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

}




