package com.unis.flowable.server.service;


import com.unis.common.utils.CurrentUtil;
import com.unis.common.utils.ResponseWrapper;
import com.unis.flowable.common.vo.GroupVO;
import com.unis.flowable.common.vo.MembershipVO;
import com.unis.flowable.common.vo.SaveGroupVO;
import com.unis.flowable.common.vo.UserVO;
import org.flowable.engine.IdentityService;
import org.flowable.idm.api.Group;
import org.flowable.idm.api.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


/**
 * @Auther:张新亮
 * @Date: 2019/7/24 0024 11:13
 * @Description:
 */
@Service
@SuppressWarnings("unchecked")
public class FlowGroupService {
    @Autowired
    private IdentityService identityService;


    /**
     * 添加用户角色
     * @param saveGroupVOs
     * @return
     */
	@SuppressWarnings("rawtypes")
	public int save(List<SaveGroupVO> saveGroupVOs) {
        List<MembershipVO> membershipVOList=new ArrayList();
        for(SaveGroupVO saveGroupVO:saveGroupVOs){
            //保存组用户
            GroupVO groupVO=saveGroupVO.getGroupVO();
            int resultGroup=this.findByGroupId(groupVO.getId());
            if(resultGroup==0){
                Group group = identityService.newGroup(groupVO.getId());
                group.setName(groupVO.getName());
                group.setType(groupVO.getType());
                identityService.saveGroup(group);
            }
            //保存用户
            for(UserVO userVO:saveGroupVO.getUserVOList()){
                int resultUser=this.findByUserId(userVO.getId());
                MembershipVO membershipVO=new MembershipVO();
                if(resultUser==0){
                    User user=identityService.newUser(userVO.getId());
                    user.setFirstName(userVO.getFirstName());
                    user.setLastName(userVO.getLastName());
                    identityService.saveUser(user);
                }
                membershipVO.setGroupId(groupVO.getId());
                membershipVO.setUserId(userVO.getId());
                membershipVOList.add(membershipVO);
            }
        }

        //查询当前用户所属组
        for(MembershipVO membershipVO:membershipVOList){
            String userId=membershipVO.getUserId();
            List<Group> groupList=this.findByUserGroupList(userId);
            String result="no";
            for(Group group:groupList){
                //此用户已在项目组
                if(membershipVO.getGroupId().equals(group.getId())){
                  result="yes";
                  break;
                }
            }
            if("no".equals(result)){
                //将用户加入到用户组中
                identityService.createMembership(membershipVO.getUserId(),membershipVO.getGroupId());
            }
        }
        return 1;
    }


    /**
     * 查询用户所属组
     * @param userId
     * @return
     */
    public  List<Group> findByUserGroupList(String userId){
        List<Group> groupContainsUser = identityService.createGroupQuery()
                .groupMember(userId).list();
        return groupContainsUser;
    }


    /**
     * 根据名称查询角色
     * @param groupId
     * @return
     */
    public int findByGroupId(String groupId){
        Group group = identityService.createGroupQuery().groupId(groupId).singleResult();
        if(group==null){
            return 0;
        }
        return 1;

    }


    /**
     * 根据用户ID查询用户
     * @param userId
     * @return
     */
    public int findByUserId(String userId) {
        User user = identityService.createUserQuery().userId(userId).singleResult();
        if(user==null){
            return 0;
        }
        return 1;
    }


	public ResponseWrapper addGroup(GroupVO group2) {
		Group g = identityService.createGroupQuery().groupId(group2.getId()).singleResult();
		if(g==null){
			Group gg = identityService.newGroup(group2.getId());
			gg.setName(group2.getName());
			identityService.saveGroup(gg);
			return ResponseWrapper.success("保存成功");
		}
		return ResponseWrapper.error("已存在");
		
		
	}


	public ResponseWrapper addUser(UserVO group2) {
		// TODO Auto-generated method stub
		User u = identityService.createUserQuery().userId(group2.getId()).singleResult();
		if(u==null) {
			User user = identityService.newUser(group2.getId());
			user.setFirstName(group2.getFirstName());
			user.setEmail(group2.getEmail());
			identityService.saveUser(user);
			return ResponseWrapper.success("保存成功");
		} else {
			u.setFirstName(group2.getFirstName());
			u.setEmail(group2.getEmail());
			identityService.saveUser(u);
			return ResponseWrapper.success("更新成功");
		}
	}


	public ResponseWrapper addMember(MembershipVO membershipVO) {
		// TODO Auto-generated method stub
		List<Group> gs = identityService.createGroupQuery().groupMember(membershipVO.getUserId()).list();
		
		String result="no";
        for(Group group:gs){
            //此用户已在项目组
            if(membershipVO.getGroupId().equals(group.getId())){
              result="yes";
              break;
            }
        }
        if("no".equals(result)){
            //将用户加入到用户组中
            identityService.createMembership(membershipVO.getUserId(),membershipVO.getGroupId());
            return ResponseWrapper.success("保存成功");
        }
		return ResponseWrapper.error("已存在");
	}


	public void deleteMember(MembershipVO group2) {
		// TODO Auto-generated method stub
		try {
			List<Group> groups =  identityService.createGroupQuery().groupMember(group2.getUserId()).list();
			for(Group group :groups) {
				identityService.deleteMembership(group2.getUserId(), group.getId());
			}
			
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
}