package com.iamberry.wechat.handles.admin;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.iamberry.app.tool.des.MD5;
import com.iamberry.wechat.autiXSS.AntiXSS;
import com.iamberry.wechat.core.entity.AdminUtils;
import com.iamberry.wechat.core.entity.admin.AdminChildHavePermission;
import com.iamberry.wechat.core.entity.admin.AdminChildInfo;
import com.iamberry.wechat.core.entity.admin.AdminInfo;
import com.iamberry.wechat.core.entity.admin.AdminLoginDTO;
import com.iamberry.wechat.face.admin.AdminAdministratorService;
import com.iamberry.wechat.face.admin.AdminPermissionsService;


@Controller
public class AdminAdministratorHandler {
	@Autowired
	private AdminAdministratorService adminadministratorservice;
	public void setAdminAdministratorService(AdminAdministratorService adminadministratorservice) {
		this.adminadministratorservice = adminadministratorservice;
	}
	@Autowired
	private AdminPermissionsService adminPermissionsService;
	public void setAdminPermissionsService(AdminPermissionsService adminPermissionsService) {
		this.adminPermissionsService = adminPermissionsService;
	}
	private MD5 md5;
	public AdminAdministratorHandler() throws Exception {
		md5 = new MD5("inlongadMD5");
	}
	@Autowired
	private AdminUtils adminUtils;
	public void setAdminUtils(AdminUtils adminUtils) {
		this.adminUtils = adminUtils;
	}
	/**
	 * 进入新增二级管理员界面
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 * 
	 * @author LJK
	 * create date : 2015年12月24日16:11:28
	 */
	@RequestMapping("admin/admin/toaddUI")
	public ModelAndView toAddUI() throws Exception {
		ModelAndView mv = new ModelAndView("admin/admin/addUI");
		return mv;
	}
	/**
	 * 新增二级管理员
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 * 
	 * @author LJK
	 * create date : 2015年12月24日16:07:39
	 */
	@RequestMapping("admin/admin/addUI")
	@ResponseBody
	public String addUI(HttpServletRequest request,HttpServletResponse response,AdminChildInfo adminchildinfo) throws Exception {
		Map<String,String> adminMap = new HashMap<String,String>();
		if(adminchildinfo!=null){
			if(adminchildinfo.getAdminLoginName()!=null){
				if(adminadministratorservice.selectAdminChildInfoByName(adminchildinfo.getAdminLoginName())!=null){
					/*adminMap.put("adminMsg", "用戶已存在!");*/
					return "{\"status\":\"用戶已存在!\"}" ;
				}
			}
			md5 = new MD5("inlongadMD5");
			AdminInfo admininfo = (AdminInfo) adminUtils.getLoginAdminUser(request.getSession());//取得session中的登錄用戶
			adminchildinfo.setAdminLoginPwd(md5.encrypt(adminchildinfo.getAdminLoginPwd()));//密碼加密
			adminchildinfo.setAdminCreateAdminId(admininfo.getAdminId());//添加创建人
			adminchildinfo.setAdminStatus(2);//默认为禁止使用
			adminchildinfo.setAdminCreateDate(new Date());//添加创建时间
		}
		adminadministratorservice.insertadmin(adminchildinfo);
		/*adminMap.put("adminMsg", "添加成功!");*/
		return "{\"status\":\"添加成功!\"}" ;
	}
	/**
	 * 查看二级管理员
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 * @author LJK
	 * create date : 2015年12月24日16:08:49
	 */
	@RequestMapping("admin/admin/listUI")
	public ModelAndView listUI(@RequestParam(value="pageNO",defaultValue="1")
		Integer pageNO) throws Exception {
		ModelAndView mv = new ModelAndView("admin/admin/listUI");
		int pageSize = 3;
		List<AdminChildInfo> adminchildinfoList = adminadministratorservice.selectAdminChildInfoByList(pageNO,pageSize);
		for(AdminChildInfo adminChildInfo : adminchildinfoList){
			adminChildInfo.setAdminLoginPwd(adminUtils.encryptObject(adminChildInfo.getAdminId(),"admin"));
		}
		mv.addObject("adminchildinfoList",adminchildinfoList);
		mv.addObject("pageNO", pageNO);
		mv.addObject("pageSize", adminadministratorservice.selectAdminChildInfoByCount(pageSize));
		mv.addObject("url","/admin/admin/listUI?pageNO=");
		return mv;
	}
	/**
	 * 删除二级管理员
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 * @author LJK
	 * create date : 2015年12月24日16:08:49
	 */
	@RequestMapping("admin/admin/deleteUI")
	@ResponseBody
	public String deleteUI(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String[] alladminid = request.getParameterValues("deladminid");
		String adminid = request.getParameter("objVal");
		if(adminid!=null){
		int msg = adminadministratorservice.deleteAdminChildInfoById(adminid);
			if(msg == 0){
				return "{\"status\":\"删除失败！\"}" ;
			}
		}else if(alladminid!=null){
			for(int i = 0;i<= alladminid.length-1;i++){
				int msg = adminadministratorservice.deleteAdminChildInfoById(alladminid[i]);
				if(msg == 0){
					return "{\"status\":\"删除失败！\"}" ;
				}
			}
		}
		 return "{\"status\":\"删除成功！\"}";
	}
	
	/**
	 * 打开二级管理员修改界面
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 * @author LJK
	 * create date : 2015年12月25日15:46:53
	 */
	@RequestMapping("admin/admin/toupdateUI/{adminid}")
	public ModelAndView toUpdateUI(HttpServletRequest request,
			HttpServletResponse response,
			@PathVariable("adminid") String adminid) throws Exception {
		ModelAndView mv = new ModelAndView("admin/admin/updateUI");
			if(adminid!=null){
				AdminChildInfo adminchildinfo =	adminadministratorservice.selectAdminChildInfoById(adminid);
				if(adminchildinfo!=null){
					adminchildinfo.setAdminLoginPwd(new AdminUtils().decryptObject(adminchildinfo.getAdminLoginPwd(), "admin"));//密碼解密
					mv.addObject("adminchildinfo",adminchildinfo);
				}
			}
		return mv;
	}
	
	/**
	 * 修改二级管理员
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 * @author LJK
	 * create date : 2015年12月24日16:08:49
	 */
	@RequestMapping("admin/admin/updateUI")
	@ResponseBody
	public String updateUI(HttpServletRequest request,
			HttpServletResponse response,AdminChildInfo adminchildinfo) throws Exception {
		if(adminchildinfo!=null){
		Integer msg = adminadministratorservice.updateAdminChildInfoById(adminchildinfo);
			if(msg == 0){
				return "{\"status\":\"修改失败！\"}";
			}
		}
		return "{\"status\":\"修改成功！\"}";
	}
	/**
	 * 修改二级管理员是否启用权限
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 * @author LJK
	 * create date : 2015年12月24日16:08:49
	 */
	@RequestMapping("admin/admin/updatePermissions")
	@ResponseBody
	public String updatePermissions(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String adminid = request.getParameter("adminid");
		String adminStatus = request.getParameter("adminStatus");
		if(adminStatus.equals("1")){
			adminStatus = "2";
		}else if(adminStatus.equals("2")){
			adminStatus = "1";
		}
		Integer msg = adminadministratorservice.updatePermissionsById(adminid,adminStatus);
			if(msg == 0){
				return "{\"status\":\"修改失败！\"}";
			}
		return "{\"status\":\"修改成功！\"}";
	}
	
	/**
	 * 打开二级管理员权限修改界面
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 * @author LJK
	 * create date : 2015年12月25日15:46:53
	 */
	@RequestMapping("admin/admin/toupdatePermissionsUI/{adminid}")
	public ModelAndView toupdatePermissionsUI(HttpServletRequest request,
			HttpServletResponse response,ModelMap model,
			@PathVariable("adminid") Integer adminid) throws Exception {
		ModelAndView mv = new ModelAndView("admin/admin/updatePermissions");
			if(adminid!=null){
				AdminChildInfo adminchildinfo =	adminadministratorservice.selectAdminChildInfoById(adminid.toString());
				List<AdminChildHavePermission> adminChildHavePermission = adminPermissionsService.selectPermissionById(adminid);
				if(adminChildHavePermission.size()>0){
					mv.addObject("adminChildHavePermission",adminChildHavePermission);
				}
				if(adminchildinfo!=null){
					mv.addObject("adminchildinfo",adminchildinfo);
				}
			}
		return mv;
	}
/**
 * 二级管理员权限修改
 * @param request
 * @param response
 * @param adminchildinfo
 * @return
 * @throws Exception
 */
	@RequestMapping("admin/admin/updateAllPermissions")
	@ResponseBody
	public String updateAllPermissions(HttpServletRequest request,HttpServletResponse response,AdminChildHavePermission adminChildHavePermission) throws Exception {
		String[] eid = request.getParameterValues("eid");//获取用户选择的所有权限
		String adminChildId = request.getParameter("adminChildId");
		if(adminChildId!=null){
			adminPermissionsService.deletePermissionById(Integer.valueOf(adminChildId));//删除所有权限
		}
		 if(eid!=null){
	            for (int i = 0; i < eid.length; i++) {//循环添加所有权限
	                adminChildHavePermission.setPermissionId(Integer.valueOf(eid[i].trim()));
	                adminPermissionsService.insertPermissionById(adminChildHavePermission);
	            }
	        }
		return "{\"status\":\"添加成功!\"}";
	}

	/**
	 * 迷糊查找管理员界面
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 * @author LJK
	 * create date : 2015年12月25日15:46:53
	 */
	@RequestMapping("admin/admin/toSelectAdministrator")
	public ModelAndView toSelectAdministrator(@RequestParam(value="pageNO",defaultValue="1")
	Integer pageNO,HttpServletRequest request) throws Exception {
			ModelAndView mv = new ModelAndView("admin/admin/listUI");
			String adminLoginName = request.getParameter("administratorName");
			String adminloginname = "%"+adminLoginName+"%";
			int pageSize = 3;
			if(adminLoginName!=null){
				List<AdminChildInfo> adminchildinfoList = adminadministratorservice.selectAdminChildInfoByNameList(adminloginname,pageNO,pageSize);
				for(AdminChildInfo adminChildInfo : adminchildinfoList){
					adminChildInfo.setAdminLoginPwd(adminUtils.encryptObject(adminChildInfo.getAdminId(),"admin"));
				}
				mv.addObject("adminLoginName", AntiXSS.xssEncode(adminLoginName));
				mv.addObject("adminchildinfoList",adminchildinfoList);
				mv.addObject("pageNO", pageNO);
				mv.addObject("pageSize", adminadministratorservice.selectAdminChildInfoByNameCount(adminloginname, pageSize));
				mv.addObject("url","/admin/admin/toSelectAdministrator?administratorName="+adminLoginName+"&pageNO=");
			}
		return mv;
	}
	//进入二级管理员修改界面
	@RequestMapping("admin/admin/toUpdateAdmin")
	public ModelAndView toUpdateAdmin(HttpServletRequest request){
		ModelAndView mv = new ModelAndView("admin/admin/updateAdmin");
		HttpSession session = request.getSession(true);	
		AdminInfo adminInfo =	(AdminInfo)session.getAttribute("login_admin_userinfo");
		mv.addObject("adminName", adminInfo.getAdminLoginName());
		mv.addObject("adminNameID", adminInfo.getAdminId());
		return mv;
	}
	//进入超级管理员修改界面
	@RequestMapping("admin/admin/toUpdateSuperAdmin")
	public ModelAndView toUpdateSuperAdmin(HttpServletRequest request){
		HttpSession session = request.getSession(true);		
		ModelAndView mv = new ModelAndView("admin/admin/updateSuperAdmin");
		AdminInfo adminInfo =	(AdminInfo)session.getAttribute("login_admin_userinfo");
		mv.addObject("adminName", adminInfo.getAdminLoginName());
		mv.addObject("adminNameID", adminInfo.getAdminId());
		return mv;
	}
	//超级管理员修改
	@RequestMapping("admin/admin/updateSuperAdminPwd")
	@ResponseBody
	public String updateSuperAdminPwd(HttpServletRequest request,AdminLoginDTO dto) throws Exception{
		HttpSession session = request.getSession(true);		
				// 验证码
				if (!adminUtils.checkVerifyCode(request.getSession(), dto.getVerifyCode())) {
					return "验证码错误，请重试!";
				}
				AdminInfo adminInfo = (AdminInfo)session.getAttribute("login_admin_userinfo");
				adminInfo.setAdminLoginPwd(request.getParameter("adminLoginPwd"));
				adminInfo.setAdminLoginPwd(md5.encrypt(adminInfo.getAdminLoginPwd()));//密码加密
				adminadministratorservice.updateSuperAdminByPwd(adminInfo);
				//一旦修改成功就改变session的值
				session.setAttribute("login_admin_userinfo", adminInfo);
				return "{\"status\":\"修改成功!\"}";
	}
	//二级管理员修改
	@RequestMapping("admin/admin/updateAdminPwd")
	@ResponseBody
	public String updateAdmin(HttpServletRequest request,AdminLoginDTO dto,AdminChildInfo adminchildinfo) throws Exception{
		HttpSession session = request.getSession(true);		
				// 验证码
				if (!adminUtils.checkVerifyCode(request.getSession(), dto.getVerifyCode())) {
					return "{\"status\":\"验证码错误，请重试!\"}";
				}
				AdminInfo adminInfo =	(AdminInfo)session.getAttribute("login_admin_userinfo");
				adminchildinfo.setAdminId(adminInfo.getAdminId());
				adminchildinfo.setAdminLoginPwd(request.getParameter("adminLoginPwd"));
				//加密新密码
				adminchildinfo.setAdminLoginPwd(md5.encrypt(adminchildinfo.getAdminLoginPwd()));//密码加密
//System.out.println(adminchildinfo.getAdminLoginPwd());
				adminadministratorservice.updateAdminByPwd(adminchildinfo);
				//一旦修改成功就改变session的值
				session.setAttribute("login_admin_userinfo", adminInfo);
				return "{\"status\":\"修改成功!\"}";
	}
}
