package com.xtd.project.activiti.event.listener;

import com.xtd.common.utils.StringUtils;
import com.xtd.project.activiti.event.AddGroupEvent;
import com.xtd.project.activiti.event.AddSysUserEvent;
import com.xtd.project.activiti.event.DeleteGroupEvent;
import com.xtd.project.activiti.event.DeleteSysUserEvent;
import com.xtd.project.system.domain.SysDept;
import com.xtd.project.system.domain.SysUser;
import org.activiti.engine.IdentityService;
import org.activiti.engine.identity.Group;
import org.activiti.engine.identity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

@Component
public class EventListeners {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private IdentityService identityService;

    /**
     * 新增用户和
     *
     * @param addSysUserEvent
     */
    @EventListener
    public void addUser(AddSysUserEvent addSysUserEvent) {
        SysUser sysUser = addSysUserEvent.getSysUser();
        String userId = sysUser.getUserId().toString();
        String userName = sysUser.getUserName();
        User user = identityService.createUserQuery().userId(userId).singleResult();
        if(null==user){
            user = identityService.newUser(userId);
        }
        user.setFirstName(userName);
        identityService.saveUser(user);
        Long deptId = sysUser.getDeptId();
        if (StringUtils.isNotNull(deptId)) {
            String groupId = deptId.toString();
            identityService.createMembership(userId, groupId);
        }
    }

    @EventListener
    public void deleteUser(DeleteSysUserEvent deleteSysUserEvent) {
        Long id = deleteSysUserEvent.getId();
        identityService.deleteUser(id.toString());
    }

    @EventListener
    public void addGroup(AddGroupEvent addGroupEvent) {
        SysDept sysDept = addGroupEvent.getSysDept();
        String deptName = sysDept.getDeptName();
        String deptId = sysDept.getDeptId().toString();
        Group group = identityService.createGroupQuery().groupId(deptId).singleResult();
        if(null==group){
            group = identityService.newGroup(deptId);
        }
        group.setName(deptName);
        identityService.saveGroup(group);
    }

    @EventListener
    public void deleteGroup(DeleteGroupEvent deleteGroupEvent) {
        Long id = deleteGroupEvent.getId();
        identityService.deleteGroup(id.toString());
    }
}
