package cn.stylefeng.workflow.instance.modular.task.taskopt.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.stylefeng.workflow.api.entity.instance.RuntimeNode;
import cn.stylefeng.workflow.api.entity.task.RuTask;
import cn.stylefeng.workflow.api.enums.TaskTypeEnum;
import cn.stylefeng.workflow.api.pojo.InstanceContext;
import cn.stylefeng.workflow.instance.api.RuntimeNodeApi;
import cn.stylefeng.workflow.instance.api.WorkflowStatusApi;
import cn.stylefeng.workflow.instance.modular.task.pojo.operate.CopyToRequest;
import cn.stylefeng.workflow.instance.modular.task.service.RuTaskService;
import cn.stylefeng.workflow.instance.modular.task.taskopt.TaskCopyToService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Set;

@Service
public class TaskCopyToServiceImpl implements TaskCopyToService {

    @Resource
    private WorkflowStatusApi workflowStatusApi;

    @Resource
    private RuntimeNodeApi runtimeNodeApi;

    @Resource
    private RuTaskService ruTaskService;

    @Override
    public void copyTo(CopyToRequest copyToRequest) {

        Set<Long> copyToUserIdList = copyToRequest.getCopyToUserIdList();

        if (ObjectUtil.isEmpty(copyToUserIdList)) {
            return;
        }

        RuTask ruTask = ruTaskService.getById(copyToRequest.getTaskId());
        if (ruTask == null) {
            return;
        }

        InstanceContext instanceContext = workflowStatusApi.buildInstanceContext(ruTask.getInstanceId());

        RuntimeNode runtimeNode = runtimeNodeApi.getRuntimeNodeById(ruTask.getRuNodeId());

        for (Long userId : copyToUserIdList) {
            ruTaskService.createUserTask(userId, TaskTypeEnum.COPY, runtimeNode, instanceContext);
        }
    }

}
