package org.ccpit.base.role;

import java.io.IOException;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.ccpit.base.controller.BaseController;
import org.ccpit.base.controller.Page;
import org.ccpit.base.controller.PageRequest;
import org.ccpit.base.user.User;
import org.ccpit.base.user.UserService;
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.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * Created by Administrator on 2015/9/6.
 */
@Controller
@RequestMapping("/admin/role")
public class RoleController extends BaseController{
    @Autowired
    private RoleService roleService;
    @Autowired
    private UserService userService;

    @RequestMapping("/goinRoleListPage")
    public Object manage(){
        return new ModelAndView("admin/role/roleListPage");
    }

    @RequestMapping("/addRole")
    public void addRole(String roleName,String urlPerfixs,String description,HttpServletResponse response){
        String result = "";
        boolean flag = roleService.addRole(roleName,urlPerfixs,description);
        if(flag){
			result = "{ \"flag\": "+ flag  +", \"info\": \"数据保存成功！\" }";
		}else {
			result = "{ \"flag\": "+ flag  +", \"info\": \"数据保存失败！\" }";
		}
		try { 
			response.setContentType("text/html");
			response.getWriter().write(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
    /**
     * 
     * addRolePri:(添加角色操作权限). <br/>
     * TODO(这里描述这个方法适用条件 – 可选).<br/>
     * TODO(这里描述这个方法的执行流程 – 可选).<br/>
     * TODO(这里描述这个方法的使用方法 – 可选).<br/>
     * TODO(这里描述这个方法的注意事项 – 可选).<br/>
     *
     * @author dingwei
     * @return
     * @since JDK 1.6
     */
    @RequestMapping("/addRolePri")
    public void addRolePri(HttpServletRequest request,HttpServletResponse response){
    	String result = "";
    	String roleId = request.getParameter("roleId");
    	String urlPrefixs = request.getParameter("priIds");
        boolean flag = roleService.editRole(Long.valueOf(roleId), "", urlPrefixs, "");
        if(flag){
			result = "{ \"flag\": "+ flag  +", \"info\": \"数据保存成功！\" }";
		}else {
			result = "{ \"flag\": "+ flag  +", \"info\": \"数据保存失败！\" }";
		}
		try { 
			response.setContentType("text/html");
			response.getWriter().write(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
    
     @RequestMapping("/editRole/{id}")
     public void editRole(@PathVariable long id,String roleName,String urlPerfixs,String description,HttpServletResponse response){
    	String result = "";
    	boolean flag = roleService.editRole(id, roleName, urlPerfixs,description);
        if(flag){
			result = "{ \"flag\": "+ flag  +", \"info\": \"数据保存成功！\" }";
		}else {
			result = "{ \"flag\": "+ flag  +", \"info\": \"数据保存失败！\" }";
		}
		try { 
			response.setContentType("text/html");
			response.getWriter().write(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
    }

    @RequestMapping("/userRoles/{id}")
    @ResponseBody
    public Object userRoles(@PathVariable long id){
        User user = userService.getUser(id);
        if (user!=null){
            return userService.getUserRoles(user);
        }
        return "false";
    }

    @RequestMapping("/delRoles")
    @ResponseBody
    public Object delRoles(HttpServletRequest request){
        Map<String, Object> map = new HashMap<String, Object>();
		String jsonIds = request.getParameter("ids");
		JSONArray jsonArray = JSONArray.fromObject(jsonIds);
		Object[] ids = jsonArray.toArray();
		for(Object str : ids){
			boolean flag = roleService.deleteRole((Integer) str);
		}
		map.put("flag", true);
		map.put("info", "数据删除成功！");
        return map;
    }

    @RequestMapping("/saveUserRoles/{id}")
    @ResponseBody
    public Object saveUserRoles(@PathVariable long id,HttpServletRequest request,String[] ids){
        System.out.println(ids);
        User user = userService.getUser(id);
        //todo save
        Map<String, Object> map = new HashMap<String, Object>();
        JSONArray jsonArray = JSONArray.fromObject(ids);
        Object[] arr = jsonArray.toArray();
        Long[] longs = new Long[arr.length];
        for (int i=0;i<arr.length;i++){
            longs[i] = Long.parseLong(arr[i].toString());
        }
        boolean flag = userService.saveUserRoles(user,longs);
        if (flag){
            map.put("flag", true);
            map.put("info", "数据删除成功！");
        }else{
            map.put("flag", false);
            map.put("info", "保存失败！");
        }

        return map;
    }

    @RequestMapping("/getAllRoles")
    @ResponseBody
    public Object getAllRoles(HttpServletRequest request){
        PageRequest pageRequest = getPage(request);
        String roleName = request.getParameter("roleName");
        StringBuffer hql = new StringBuffer("from Role where 1=1");
        if(null == roleName){
        	
        }else {
        	if(null != roleName){
        		hql.append(" and roleName like '%" + roleName +"%'");
        	}
        }
        List<Role> pageRole = roleService.getAll(hql.toString());
        return pageRole;
    }
    
    @RequestMapping("/getRoleByID")
    @ResponseBody
     public Role getRoleByID(HttpServletRequest request){
    	String roleId = request.getParameter("roleId");
    	Role role = null;
    	if(null != roleId){
    		role = roleService.get(Long.valueOf(roleId)); 
    	}
        return role;
    }
    
    @RequestMapping("/getRolesList")
	@ResponseBody
	public Object getRolesList(HttpServletRequest request){
		List<Role> listBo = roleService.getAllRoles();
		List list = new ArrayList();
		if(null != listBo){
			for(int i=0;i<listBo.size();i++){
				Map result = new HashMap();
				result.put("id", listBo.get(i).getId());
				result.put("text", listBo.get(i).getRoleName());
				list.add(result);
			}
		}
		return list;
	}
}
