package cn.stylefeng.workflow.instance.modular.task.strategy.samesubmit.base;

import cn.hutool.extra.spring.SpringUtil;
import cn.stylefeng.workflow.api.entity.design.Node;
import cn.stylefeng.workflow.api.entity.task.RuTask;
import cn.stylefeng.workflow.api.enums.NodeTypeEnum;
import cn.stylefeng.workflow.api.enums.strategy.SamePersonApprovalPolicyEnum;
import cn.stylefeng.workflow.api.pojo.InstanceContext;
import cn.stylefeng.workflow.instance.modular.task.taskopt.TaskDelegateService;

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

public abstract class SameSubmitRule {

    public abstract SamePersonApprovalPolicyEnum getSameSubmitRuleType();

    public abstract RuTask processTask(RuTask originTask, Long applicantUserId, Long applicantOrgId);

    public List<RuTask> processSameSubmit(Node currentNode, List<RuTask> currentApproverTaskList, InstanceContext instanceContext) {

        Integer nodeType = currentNode.getNodeType();
        if (NodeTypeEnum.START.getNodeType().equals(nodeType) || NodeTypeEnum.APPLICANT.getNodeType().equals(nodeType)) {
            return currentApproverTaskList;
        }

        Long applicantUserId = instanceContext.getRuntimeInstance().getApplicant();

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

        List<RuTask> newResultTaskList = new ArrayList<>();

        for (RuTask ruTask : currentApproverTaskList) {
            if (ruTask.getApprover().equals(applicantUserId)) {

                RuTask otherProduceTask = this.processTask(ruTask, applicantUserId, applicantOrgId);
                if (otherProduceTask != null) {

                    newResultTaskList.add(otherProduceTask);

                    TaskDelegateService taskDelegateService = SpringUtil.getBean(TaskDelegateService.class);
                    taskDelegateService.updatePointNodeUserId(currentNode, ruTask, otherProduceTask, instanceContext.getRuntimeInstance().getInstanceId(), instanceContext.getInstanceVariable());
                }


            }
        }

        newResultTaskList.addAll(currentApproverTaskList);
        return newResultTaskList;
    }


}
