package com.yihu.jw.base.service.role;

import com.yihu.jw.base.dao.role.RoleDao;
import com.yihu.jw.base.dao.role.RoleMenuDao;
import com.yihu.jw.entity.base.role.RoleDO;
import com.yihu.jw.entity.base.role.RoleMenuDO;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.rm.base.BaseRequestMapping;
import com.yihu.mysql.query.BaseJpaService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Service - 角色
 * Created by progr1mmer on 2018/8/17.
 */
@Service
public class RoleService extends BaseJpaService<RoleDO, RoleDao> {

    @Autowired
    private RoleDao roleDao;
    @Autowired
    private RoleMenuDao roleMenuDao;

    public Envelop saveRole(RoleDO roleDO, List<RoleMenuDO> list){

        RoleDO role = roleDao.save(roleDO);

        List<RoleMenuDO> rs =  roleMenuDao.findByRoleId(role.getId());

        if(rs!=null&&rs.size()>0){
            roleMenuDao.delete(rs);
        }
        if(list!=null&&list.size()>0){
            for(RoleMenuDO r:list){
                r.setRoleId(role.getId());
            }
            roleMenuDao.save(list);
        }

        return Envelop.getSuccess(BaseRequestMapping.Role.api_success);
    }

    public Boolean findRoleNameExist(String name,String saasId){
        if(StringUtils.isNotBlank(saasId)){
            List<RoleDO> list = roleDao.findByNameAndSaasIdAndStatus(name,saasId,1);
            if(list!=null&&list.size()>0){
                return true;
            }
        }else{
            List<RoleDO> list = roleDao.findByNameAndStatus(name,1);
            if(list!=null&&list.size()>0){
                return true;
            }
        }
        return false;
    }
}
