package cn.com.qmth.stmms.admin.role;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import cn.com.qmth.stmms.biz.role.service.RoleAuthService;
import cn.com.qmth.stmms.common.auth.annotation.AuthRequire;
import cn.com.qmth.stmms.common.enums.Auth;
import cn.com.qmth.stmms.common.enums.Role;

@Controller
@RequestMapping("/admin/role")
public class RoleController {

    @Autowired
    private RoleAuthService roleService;

    @RequestMapping
    @AuthRequire({ Auth.ROLE_VIEW })
    public ModelAndView list(HttpServletRequest request, @RequestParam(required = false) String message) {
        ModelAndView view = new ModelAndView("admin/role/list");
        view.addObject("message", StringUtils.trimToEmpty(message));
        view.addObject("roleList", Role.values());
        return view;
    }

    @RequestMapping(value = "/edit/{roleName}", method = RequestMethod.GET)
    @AuthRequire({ Auth.ROLE_EDIT })
    public ModelAndView updateInit(HttpServletRequest request, @PathVariable String roleName) {
        ModelAndView view = new ModelAndView("admin/role/edit");
        Role role = roleService.findRoleByName(roleName);
        if (role != null) {
            Set<Auth> set = roleService.findAuthByRole(role);
            Map<String, Auth> map = new HashMap<String, Auth>();
            if (set != null) {
                for (Auth auth : set) {
                    map.put(auth.getName(), auth);
                }
            }
            view.addObject("role", role);
            view.addObject("authMap", map);
            view.addObject("authList", Auth.values());
        } else {
            view = new ModelAndView("redirect:/admin/role/list").addObject("message", "角色不存在");
        }
        return view;
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @AuthRequire({ Auth.ROLE_EDIT })
    public ModelAndView update(HttpServletRequest request, @RequestParam String name, @RequestParam String[] authNames) {
        Role role = roleService.findRoleByName(name);
        String message = "";
        if (role != null) {
            roleService.updateRoleAuth(role.getName(), authNames);
            message = "角色保存成功";
        } else {
            message = "角色不存在";
        }
        return new ModelAndView("redirect:/admin/role").addObject("message", message);
    }
}
