package com.yihu.hos.system.service;

import com.yihu.hos.web.framework.model.ActionResult;
import com.yihu.hos.web.framework.model.Result;
import com.yihu.hos.system.dao.intf.IRoleDao;
import com.yihu.hos.system.model.SystemRole;
import com.yihu.hos.system.service.intf.IRoleManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * Created by chenweida on 2016/1/19.
 */
@Service("roleManager")
public class RoleManager implements IRoleManager {
    @Autowired
    private IRoleDao roleDao;

    @Override
    public Result getRoleList(Map<String, Object> params) throws Exception {

        return roleDao.getRoleList(params);
    }

    @Override
    public SystemRole getRoleById(String roleId) throws Exception {
        return roleDao.getEntity(SystemRole.class, roleId);
    }

    @Transactional
    public Result addRole(SystemRole obj) throws Exception {
        SystemRole roleTemp = roleDao.getRoleByName(obj.getName());
        if (roleTemp != null) {
            return Result.error("角色名称已经存在");
        }
        roleDao.saveEntity(obj);
        return Result.success("保存成功");
    }

    @Transactional
    public Result updateRole(SystemRole obj) throws Exception {
        SystemRole roleTemp = roleDao.getRoleByNameWithOutId(obj.getName(), obj.getId());
        if (roleTemp != null) {
            return Result.error("角色名称已经存在");
        }
        SystemRole systemRole = roleDao.getEntity(SystemRole.class, obj.getId());
        systemRole.setName(obj.getName());
        systemRole.setRemark(obj.getRemark());
        return Result.success("更新成功");
    }

    @Transactional
    public Result activityRole(String roleid, String activityFlag) throws Exception {
        try {
            roleDao.activityRole(roleid, activityFlag);
            return new ActionResult(true, "状态修改成功！");
        } catch (Exception ex) {
            return new ActionResult(false, "状态修改失败！");
        }
    }

    @Transactional
    public Result deleteRole(String id) throws Exception {
        SystemRole sr = roleDao.getEntity(SystemRole.class, id);
        roleDao.deleteEntity(sr);
        return Result.success("删除成功");
    }
}
