package com.codvision.workflow.listener.task;


import com.codvision.auth.entity.Org;
import com.codvision.auth.entity.SysRole;
import com.codvision.auth.entity.SysUser;
import com.codvision.auth.service.IOrgService;
import com.codvision.auth.service.ISysRoleService;
import com.codvision.auth.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import org.flowable.engine.TaskService;
import org.flowable.task.service.delegate.DelegateTask;
import org.springframework.stereotype.Component;

import static com.codvision.workflow.constant.WorkFlowConstant.*;


/**
 * 任务延期申请审核人员配置监听器 （任务监听器 事件类型 -> create）
 * @author hxl
 */
@RequiredArgsConstructor
@Component(value = "workFlowTaskDelayReviewerConfigListener")
public class WorkFlowTaskDelayReviewerConfigListener {

    private final TaskService taskService;
    private final ISysUserService sysUserService;
    private final IOrgService orgService;
    private final ISysRoleService sysRoleService;

    public void setUid(DelegateTask delegateTask, Integer uid) {
        if (uid == null) {
            return;
        }

        SysUser sysUser = sysUserService.getById(uid);
        if (sysUser == null) {
            return;
        }

        taskService.setVariable(delegateTask.getId(), WORK_FLOW_DELAY_REVIEWER_CONFIG_USER, uid);
    }

    public void setOid(DelegateTask delegateTask, Integer oid, Integer roleId) {
        if (oid == null && roleId == null) {
            return;
        }

        if (roleId != null) {
            SysRole sysRole = sysRoleService.getById(roleId);
            if (sysRole == null) {
                return;
            }

            taskService.setVariable(delegateTask.getId(), WORK_FLOW_DELAY_REVIEWER_CONFIG_ROLE, roleId);
        }

        if (oid != null) {
            Org org = orgService.getById(oid);
            if (org == null) {
                return;
            }

            taskService.setVariable(delegateTask.getId(), WORK_FLOW_DELAY_REVIEWER_CONFIG_ORG, oid);
        }
    }
}
