package com.tykj.workflowcore.user.service.impl;

import com.tykj.workflowcore.user.dao.AuthorityDao;
import com.tykj.workflowcore.user.dao.AuthorityOrganizationDao;
import com.tykj.workflowcore.user.dao.UserAuthorityDao;
import com.tykj.workflowcore.user.pojo.Authority;
import com.tykj.workflowcore.user.pojo.AuthorityOrganization;
import com.tykj.workflowcore.user.pojo.UserAuthority;
import com.tykj.workflowcore.user.service.AuthorityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AuthorityServiceImpl implements AuthorityService {
    @Autowired
    private AuthorityDao authorityDao;
    @Autowired
    private UserAuthorityDao userAuthorityDao;
    @Autowired
    private AuthorityOrganizationDao authorityOrganizationDao;

    @Override
    public Authority save(Authority authority) {
        Authority authority1 = authorityDao.save(authority);
        if (authority1 != null){
            return authority1;
        }
        return null;
    }

    @Override
    public Authority update(Authority authority) {
        Authority authority1 = authorityDao.save(authority);
        if (authority1 != null){
            return authority1;
        }
        return null;
    }

    @Override
    public void delete(Integer id) {
        authorityDao.deleteById(id);
        //权限删除之后  权限和用户  组织架构之间的关系都需要解除
        List<UserAuthority> userAuthorityList = userAuthorityDao.findByAuthorityId(id);
        for (UserAuthority userAuthority : userAuthorityList) {
            userAuthorityDao.delete(userAuthority);
        }

        List<AuthorityOrganization> authorityOrganizationList = authorityOrganizationDao.findByAuthId(id);
        for (AuthorityOrganization authorityOrganization : authorityOrganizationList) {
            authorityOrganizationDao.delete(authorityOrganization);
        }

    }

    @Override
    public Authority findById(Integer id) {
        Authority authority = authorityDao.findById(id).get();
        if (authority!= null){
            return authority;
        }
        return null;
    }

    @Override
    public List<Authority> findByType(Integer type) {
        List<Authority> authorityList = authorityDao.findByType(type);
        if (authorityList != null){
            return authorityList;
        }
        return null;
    }

    @Override
    public List<Authority> findAll() {
        List<Authority> authorityList = authorityDao.findAll();
        if (authorityList != null){
            return authorityList;
        }
        return null;
    }

    @Override
    public List<Authority> findByNameLike(String name) {
        List<Authority> authorityList = authorityDao.findByNameLike("%" + name + "%");
        if (authorityList!= null){
            return authorityList;
        }
        return null;
    }
}
