package com.zcxk.process.activiti.listener;

import com.alibaba.fastjson.JSON;

import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.delegate.event.ActivitiEntityEvent;
import org.activiti.engine.delegate.event.ActivitiEvent;
import org.activiti.engine.delegate.event.ActivitiEventListener;
import org.activiti.engine.delegate.event.ActivitiEventType;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.activiti.engine.task.IdentityLink;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * 工单处理提醒监听器
 *
 * @author wilian.peng
 * @date 2019/12/25
 */
@Slf4j
@Component
public class WorkOrderEventListener implements ActivitiEventListener {

    @Override
    public void onEvent(ActivitiEvent event) {
        if (event.getType() == ActivitiEventType.TASK_CREATED
                || event.getType() == ActivitiEventType.TASK_ASSIGNED) {
            ActivitiEntityEvent entityEvent = (ActivitiEntityEvent) event;
            TaskEntity taskEntity = (TaskEntity) entityEvent.getEntity();
            // 指派用户
            String assignee = taskEntity.getAssignee();
            Set<String> users = new HashSet<>();
            if (StringUtils.isNotEmpty(assignee)) {
                users.add(assignee);
            }
            Set<IdentityLink> candidates = taskEntity.getCandidates();
            for (IdentityLink candidate : candidates) {
                if (StringUtils.isNotEmpty(candidate.getUserId())) {
                    users.add(candidate.getUserId());
                }
            }
            // 发送新工单通知
            String orderNo = taskEntity.getProcessInstance().getBusinessKey();
            String tenantId = taskEntity.getProcessInstance().getTenantId();
            log.info("发送新工单通知,users = {}", JSON.toJSONString(users));
       /*     WorkOrderService workOrderService = (WorkOrderService) SpringContextUtil.getBean(WorkOrderService.class);
            workOrderService.newOrderNotify(users, orderNo,Integer.parseInt(tenantId));
       */ }
    }

    @Override
    public boolean isFailOnException() {
        return false;
    }
}
