package com.cftech.sys.controller;

import com.cftech.accounts.model.MpAccountsEntity;
import com.cftech.core.scope.OrderType;
import com.cftech.core.sql.Conds;
import com.cftech.core.sql.Sort;
import com.cftech.core.util.OutputJSONUtil;
import com.cftech.core.util.StringUtils;
import com.cftech.mchaccounts.mch.model.MchAccounts;
import com.cftech.mchaccounts.mch.service.MchAccountsService;
import com.cftech.sys.model.Role;
import com.cftech.sys.model.User;
import com.cftech.sys.model.UserRole;
import com.cftech.sys.security.PermissionSign;
import com.cftech.sys.security.UserUtils;
import com.cftech.sys.service.RoleService;
import com.cftech.sys.service.UserService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lisw
 * @date 2016年9月20日 下午5:35:08
 *
 */
@Controller
@RequestMapping("/a/manageuser")
public class ManageUserController 
{
    @Resource
    private UserService userService;
    
    @Resource
    private RoleService roleService;

    @Autowired
	private MchAccountsService mchAccountsService;

	//管理后台用户列表
    @RequiresPermissions(value= PermissionSign.USER_VIEWS)
    @RequestMapping(value = "/userlist")
    public String userlist(Model model,User user) {
    	model.addAttribute("user",user);
        return "manageuser/userlist";
    }
    //修改用户 跳转页面 
    @RequiresPermissions(value=PermissionSign.USER_EDIT)
    @RequestMapping(value = "/userfromDetail")
    public String userupdatefrom(HttpServletRequest request, HttpServletResponse response,Model model,Long id) 
    {
    	//获得角色信息 
    	List<Role> roles = roleService.selectAll(null);
		JSONArray array = new JSONArray();


		Conds conds = new Conds();
		conds.equal("del_flag", 0);
		Sort sort = new Sort("update_time", OrderType.DESC);

		Map<String, Object> params = new HashMap<String, Object>();
		params.put("conds", conds);
		params.put("sort", sort);


		List<MchAccounts> accounts = mchAccountsService.getAll(params);
		for(MchAccounts entity :accounts){
			List<UserRole> userRoles = roleService.selectRolesByUserAccountsId(id, entity.getId());
			if(userRoles!=null && userRoles.size()>0){
				String rolesTemp = "";
				for(UserRole userRole : userRoles){
					rolesTemp+=","+userRole.getRoleId()+",";
				}
				JSONObject rtnJson = new JSONObject();
				rtnJson.put("accountsId",entity.getId());
				rtnJson.put("roles",rolesTemp);
				array.add(rtnJson);
			}
		}



    	model.addAttribute("roles", roles);
		model.addAttribute("accounts", accounts);
		model.addAttribute("userRoles", array.toString());
    	if(id!=null)
    	{
    		model.addAttribute("user", userService.fetchById(id));
    	}
        return "manageuser/userupdate";
    }


    //添加用户 跳转页面
    @RequiresPermissions(value=PermissionSign.USER_EDIT)
		@RequestMapping(value = "/userform")
    public String useradd(HttpServletRequest request, HttpServletResponse response,Model model,Long id) 
    {
    	//获得角色信息 
    	List<Role> roles = roleService.selectAll(null);
		Conds conds = new Conds();
		conds.equal("del_flag", 0);
		Sort sort = new Sort("update_time", OrderType.DESC);

		Map<String, Object> params = new HashMap<String, Object>();
		params.put("conds", conds);
		params.put("sort", sort);
		List<MchAccounts> accounts = mchAccountsService.getAll(params);
		model.addAttribute("accounts",accounts);
		model.addAttribute("roles", roles);

		return "manageuser/useradds";
    }
    
    @RequestMapping("removeUser")
    @ResponseBody
    public JSONObject removeUser(Long id){
    	JSONObject rtnJson = new JSONObject();
    	try {
    		User user=userService.fetchById(id);
        	if(user!=null){
        		userService.delete(id);
        		rtnJson.put("errorNo",0);
        	}else{
        		rtnJson.put("errorNo",1);
        	}
		} catch (Exception e) {
			rtnJson.put("errorNo",1);
		}
    	return rtnJson;
    }

    
    //修改用户
	@RequestMapping(value = "/userupdate")
	public void userupdate(User user, HttpServletRequest request, HttpServletResponse response) {
		try {
			JSONObject returnObj = new JSONObject();
			returnObj.put("errorNo", "1");
			StringBuffer tmp = new StringBuffer();
			userService.clearUserRole(user.getId());
			for (int i = 0; i >= 0; i++) {
				String accounts = request.getParameter("account" + i);
				String[] roles = request.getParameterValues("roles" + i + "[]");
				if (StringUtils.isBlank(accounts) && (roles == null || roles.length == 0)) {
					break;
				}
				if (roles != null) {
					for (String role : roles) {
						tmp.append("'" + role + "',");
					}
				}
				user.setAccountsid(UserUtils.getmpaccounts(request));
				for (int k = 0; k < roles.length; k++) {
					userService.saveBatchRole(user.getId(), StringUtils.isNotBlank(roles[k]) ? Long.valueOf(roles[k]) : null, StringUtils.isNotBlank(accounts) ? Long.valueOf(accounts) : null);
				}
			}

			if (tmp.length() > 0) {
				user.setRoles(tmp.substring(0, tmp.length() - 1));
			}
			userService.update(user);
			OutputJSONUtil.convertoJSONStream(response, returnObj.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	//获取数据
    @RequestMapping(value = "/userlist/fetchdata")
    @ResponseBody
    public void getUsers(int iDisplayStart,int iDisplayLength,HttpServletResponse response,User user,HttpServletRequest request)
    {
        JSONObject returnObj = new JSONObject();
        //获得总数 
        Conds conds = new Conds();
        conds.equal("delflag", 0);
        int userCounts =  userService.count(conds);
        String username = null;
        if(user!=null && StringUtils.isNotBlank(user.getUsername())){
        	username=user.getUsername();
        	conds.like("username", username);
        }
        Sort sort = new Sort("updatetime", OrderType.DESC);
        List<User> users=userService.fetchSearchByPage(conds, sort, iDisplayStart, iDisplayLength);
        returnObj.put("iTotalRecords",userCounts);
        returnObj.put("iTotalDisplayRecords",userCounts);
        returnObj.put("aaData",JSONArray.fromObject(users));
        OutputJSONUtil.convertoJSONStream(response, returnObj.toString());
    }

    //保存用户
    @RequestMapping(value = "/adduser")
    @ResponseBody
    public void adduser( User user,HttpServletResponse response,HttpServletRequest request) {
        JSONObject returnObj = new JSONObject();
        returnObj.put("errorNo", "1");
        StringBuffer tmp = new StringBuffer();
        userService.clearUserRole(user.getId());
        userService.save(user);
        for(int i=0;i>=0;i++){
        	String accounts = request.getParameter("account"+i);
        	String [] roles = request.getParameterValues("roles"+i+"[]");
        	if(StringUtils.isBlank(accounts) && (roles==null || roles.length==0)){
        		break;
        	}
        	if(roles!=null)
            {
            	for(String role:roles)
            	{
            		tmp.append("'"+role+"',");
            	}
            }
            user.setAccountsid(UserUtils.getmpaccounts(request));
            for(int k =0;k<roles.length;k++){
            	userService.saveBatchRole(user.getId(),StringUtils.isNotBlank(roles[k])?Long.valueOf(roles[k]):null,StringUtils.isNotBlank(accounts)?Long.valueOf(accounts):null);
            }
        }
		if(tmp.length()>0)
    	{
    		user.setRoles( tmp.substring(0, tmp.length()-1) );
    	}
        userService.update(user); 
        /**
         * 解释此处为何先保存，在修改
         * 保存后获取到用户ID，才可更新关联表
         */
        OutputJSONUtil.convertoJSONStream(response, returnObj.toString());
    }
    
    //修改密码跳转页面
    @RequestMapping(value="updatePassword",method=RequestMethod.GET)
    public String updatePassword(){
    	return "manageuser/updatePassword";
    }
    //修改密码
    @RequestMapping(value="updatePassword",method=RequestMethod.POST)
    @ResponseBody
    public JSONObject updatePasswordPost(Long id,String password,String newpassword){
    	User user = new User();
    	user.setPassword(password);
    	user.setId(id);
    	Conds conds = new Conds();
    	conds.equal("id", id);
    	conds.equal("password", password);
    	conds.equal("delflag",0);
    	boolean count = userService.existByConds(conds);
    	JSONObject rtnJson = new JSONObject();
    	if(!count){
    		rtnJson.put("errorCode", "1");
    	}else{
    		user.setPassword(newpassword);
    		userService.update(user);
    		rtnJson.put("errorCode", "0");
    	}
    	return rtnJson;
    }
    
    @RequestMapping(value="checkUserName",method=RequestMethod.GET)
    @ResponseBody
    public JSONObject checkUser(String username){
    	JSONObject rtnJson = new JSONObject();
    	Conds conds = new Conds();
    	conds.equal("username",username);
    	conds.equal("delflag",0);
    	if(userService.existByConds(conds)){
    		rtnJson.put("errorNo","1");
    	}else{
    		rtnJson.put("errorNo","0");
    	}
    	return rtnJson;
    }
}

