package com.cftech.sys.controller;

import com.alibaba.fastjson.JSONPObject;
import com.cftech.accounts.model.MpAccountsEntity;
import com.cftech.accounts.service.MpAccountsService;
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.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.List;

/**
 * @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 MpAccountsService accountService;


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

		JSONArray qyArray = new JSONArray();
		List<MpAccountsEntity> qyAccounts = accountService.getAllQpAccounts();
		for(MpAccountsEntity entity :qyAccounts){
			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);
				qyArray.add(rtnJson);
			}
		}

    	model.addAttribute("accounts", accounts);
    	model.addAttribute("qyaccounts", qyAccounts);
    	model.addAttribute("roles", roles);
    	model.addAttribute("userRoles", array.toString());
    	model.addAttribute("qyUserRoles", qyArray.toString());
    	if(id!=null)
    	{
    		model.addAttribute("user", userService.fetchAuthById(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); 
    	List<MpAccountsEntity> accounts = accountService.getAllMpAccounts();
		List<MpAccountsEntity> qyAccounts = accountService.getAllQpAccounts();
		model.addAttribute("roles", roles);
    	model.addAttribute("accounts",accounts);
		model.addAttribute("qyaccounts", qyAccounts);
		return "manageuser/useradds";
    }
    
    @RequestMapping("removeUser")
    @ResponseBody
    public JSONObject removeUser(Long id){
    	JSONObject rtnJson = new JSONObject();
    	try {
    		User user=userService.fetchById(id);
        	if(user!=null){
        		user.setCustomiz_id(Long.valueOf(0));
        		userService.update(user);
        		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);
				}
			}


			for (int i = 0; i >= 0; i++) {
				String accounts = request.getParameter("qyaccount" + i);
				String[] roles = request.getParameterValues("qyroles" + 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);
		conds.equal("state",0);
        int userCounts =  userService.count(conds);
        String username = null;
        if(user!=null && StringUtils.isNotBlank(user.getUsername())){
        	username=user.getUsername();
        	conds.like("username", username);
        }
        if(UserUtils.getUser().getId()!=1){//如果当前登录人不是超管,将去除查询超管查询
        	conds.notEqual("id","1");
		}
        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();
		user.setState("0");
		user.setCustomiz_id(Long.valueOf(0));
        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));
			if(roles!=null && roles.length>0){
				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);
				}
			}

        }
		for (int i = 0; i >= 0; i++) {
			String accounts = request.getParameter("qyaccount" + i);
			String[] roles = request.getParameterValues("qyroles" + 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;
    }

    //绑定粉丝
    @RequestMapping(value = "/selectfans", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject selectfans(String fansopenid,String id){
        JSONObject rtnJson = new JSONObject();
        User user = new User();
        if(fansopenid!=null && fansopenid != ""){
            user.setEmpid(fansopenid);
        }
        if(id != null && id != ""){
            user.setId(Long.valueOf(id));
        }
        try {
            userService.update(user);
            rtnJson.put("errorNo",1);
        }catch (Exception e){
            rtnJson.put("errorNo",0);
            e.printStackTrace();
        }
        return  rtnJson;
    }
}

