package org.jeecg.modules.workFlow.flowplus.workflow.listener;

import cn.hutool.core.util.ObjUtil;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.workFlow.flowplus.workflow.entity.WflowInstanceActionRecord;
import org.jeecg.modules.workFlow.flowplus.workflow.enums.WflowActionType;
import org.jeecg.modules.workFlow.flowplus.workflow.mapper.WflowInstanceActionRecordMapper;
import org.jeecg.modules.workFlow.flowlong.engine.core.FlowCreator;
import org.jeecg.modules.workFlow.flowlong.engine.core.FlowLongContext;
import org.jeecg.modules.workFlow.flowlong.engine.core.enums.TaskEventType;
import org.jeecg.modules.workFlow.flowlong.engine.entity.FlwExtInstance;
import org.jeecg.modules.workFlow.flowlong.engine.entity.FlwTask;
import org.jeecg.modules.workFlow.flowlong.engine.entity.FlwTaskActor;
import org.jeecg.modules.workFlow.flowlong.engine.listener.TaskListener;
import org.jeecg.modules.workFlow.flowlong.engine.model.NodeAssignee;
import org.jeecg.modules.workFlow.flowlong.engine.model.NodeModel;
import org.jeecg.modules.workFlow.flowlong.engine.model.ProcessModel;
import org.jeecg.modules.workFlow.flowlong.mybatisplus.mapper.FlwExtInstanceMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.function.Supplier;
import java.util.stream.Collectors;

/**
 * 流程全局任务监听 同步方式
 *

 */
@Component
@Slf4j
public class FlowTaskListener implements TaskListener {
    @Resource
    private WflowInstanceActionRecordMapper wflowInstanceActionRecordMapper;
    @Resource
    private FlwExtInstanceMapper flwExtInstanceMapper;

    @Override
    public boolean notify(TaskEventType eventType, Supplier<FlwTask> supplier, List<FlwTaskActor> taskActors, NodeModel nodeModel, FlowCreator flowCreator) {
        if (eventType.equals(TaskEventType.cc)) {
            FlwTask flwTask = supplier.get();
            if (ObjUtil.isNull(nodeModel)) {
                log.error("节点不存在 TaskName:{} InstanceId:{}", flwTask.getTaskName(), flwTask.getInstanceId());
                return true;
            }
            // 动作执行记录
            WflowInstanceActionRecord record = new WflowInstanceActionRecord();
            record.setInstanceId(flwTask.getInstanceId().toString());
            record.setRobot(true);
            List<String> userIds = nodeModel.getNodeAssigneeList().stream()
                    .map(NodeAssignee::getId).collect(Collectors.toList());
            record.setUserIds(userIds);
            record.setActionType(WflowActionType.copy.getValue());
            // 暂时解决此处时间小于示例添加时间，后续再改进
            record.setCreateTime(new Date(DateUtils.getMillis()+5000));
            wflowInstanceActionRecordMapper.insert(record);
        }
        return true;
    }
}
