package com.palmnest.webapp.controller;

import com.alibaba.fastjson.JSONObject;
import com.palmnest.application.Constants;
import com.palmnest.application.ElementConstant;
import com.palmnest.application.core.util.FileUploadUtils;
import com.palmnest.application.core.util.PropertiesKit;
import com.palmnest.application.core.util.StringUtil;
import com.palmnest.application.dto.MenuDto;
import com.palmnest.application.dto.OrgDto;
import com.palmnest.application.dto.OutRetMsg;
import com.palmnest.application.dto.OutTreeDTO;
import com.palmnest.model.*;
import com.palmnest.model.property.TbOrganization;
import com.palmnest.service.*;
import com.palmnest.service.estateserve.EnterpriseManager;
import com.palmnest.service.repair.UserRepairTypeManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 系统管理异步请求控制器
 *
 * @author yb
 * @since 2014-05-30
 */
@Slf4j
@Controller
@RequestMapping("/admin/ajax/*")
public class AdminAjaxController {


	@Autowired
	private UserRepairTypeManager userRepairTypeManager;
	@Autowired
	private ElementGroupManager   elementGroupManager;
	@Autowired
	private AppUserService        appUserService;
	@Autowired
	private OrganizationManager   organizationManager;
	@Autowired
	private EnterpriseManager     enterpriseManager;


	private AppFunctionManager functionManager;

	@Autowired
	public void setFunctionManager(AppFunctionManager functionManager) {
		this.functionManager = functionManager;
	}

	private RoleManager roleManager;

	@Autowired
	public void setRoleManager(RoleManager roleManager) {
		this.roleManager = roleManager;
	}

	private AppMenuManager appMenuManager;

	@Autowired
	public void setAppMenuManager(AppMenuManager appMenuManager) {
		this.appMenuManager = appMenuManager;
	}

	private UserManager userManager;

	@Autowired
	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}


	public static String image_server = PropertiesKit.readPropertiesValue("image_server", "wechat.properties");

	/**
	 * 查询用户角色
	 *
	 * @param request
	 * @param response
	 * @return 树
	 */
	@RequestMapping(value = "userRoletree", method = RequestMethod.GET, produces = "application/json")
	public @ResponseBody
	List<OutTreeDTO> queryAppRoleTree(HttpServletRequest request,
									  HttpServletResponse response) {
		String     userid   = request.getParameter("userid");
		List<Role> roleList = roleManager.getRoleList();
		if (StringUtils.isNotEmpty(userid)) {
			User user = userManager.get(Long.parseLong(userid));
			return filterShowRole(roleList, user.getRoles());
		} else {
			return filterShowRole(roleList, null);
		}
	}

	public List<OutTreeDTO> filterShowRole(List<Role> all, Set<Role> userWith) {
		String           pId   = "-10";
		List<OutTreeDTO> trees = new ArrayList<OutTreeDTO>();
		OutTreeDTO       obj1  = new OutTreeDTO();
		obj1.setId(pId);
		obj1.setpId("");
		obj1.setName("所有角色");
		trees.add(obj1);

		if (userWith != null && userWith.size() > 0) {
			for (Role role : all) {
				if (ElementConstant.YESORNO_1.equals(role.getIsenalbed())) {
					OutTreeDTO obj = new OutTreeDTO();
					obj.setId(role.getId().toString());
					obj.setpId(pId);
					obj.setName(role.getName());
					for (Role r : userWith) {
						if (r.getId().intValue() == role.getId().intValue()) {
							obj.setChecked(true);
							break;
						}
					}
					trees.add(obj);
				}
			}
		} else {
			for (Role role : all) {
				if (ElementConstant.YESORNO_1.equals(role.getIsenalbed())) {
					OutTreeDTO obj = new OutTreeDTO();
					obj.setId(role.getId().toString());
					obj.setpId(pId);
					obj.setName(role.getName());
					obj.setChecked(false);
					trees.add(obj);
				}
			}
		}
		return trees;
	}

	/**
	 * 查询系统功能列表 -角色
	 *
	 * @param request
	 * @param response consumes
	 *                 produces 生产
	 */
	@RequestMapping(value = "funcRoletree", method = RequestMethod.GET, produces = "application/json")
	public @ResponseBody
	List<OutTreeDTO> queryAppFunctionTree(HttpServletRequest request,
										  HttpServletResponse response) {
		String            roleid    = request.getParameter("id");
		List<AppFunction> functions = functionManager.getAll();
		//更新
		if (StringUtils.isNotEmpty(roleid)) {
			Role role = roleManager.get(Long.parseLong(roleid));
			return filterShowFunction(functions, roleManager.queryRoleFunctionSet(role));
		}
		//新增
		else {
			return filterShowFunction(functions, null);
		}
	}

	/**
	 * 根据项目查询系统功能列表
	 *
	 * @param request
	 * @param response consumes
	 */
	@RequestMapping(value = "funcRoletreeByOrg", produces = "application/json")
	public @ResponseBody
	List<OutTreeDTO> queryAppFunctionTreeByOrg(HttpServletRequest request, HttpServletResponse response) {
		User user = (User) request.getSession().getAttribute("UserCache");

		List<AppFunction> functions = new ArrayList<AppFunction>();
		String            roleid    = request.getParameter("id");

		if (user.getUserType() < Constants.USER_TYPE_PROJECT_MANAGE) {
			//如果是系统管理员及以上角色,则加载所有功能
			functions = functionManager.getAll();
		} else {
			//否则只加载其所对应角色的功能列表
			String orgId = request.getParameter("orgId");
			//获取其role集合
			Set<Role> roleSet = user.getRoles();
			for (Role role : roleSet) {
				if (StringUtils.isNotBlank(orgId)) {
					if (null == role.getOrgId() || role.getOrgId() != Integer.parseInt(orgId))
						continue;
				}
				//获取该角色对应的功能权限列表
				List<AppFunction> roleFunction = functionManager.getFunctionListByRole(role.getId(), null);
				functions.addAll(roleFunction);

			}
		}

		//更新
		if (StringUtils.isNotEmpty(roleid)) {
			Role role = roleManager.get(Long.parseLong(roleid));
			return filterShowFunction(functions, roleManager.queryRoleFunctionSet(role));
		}
		//新增
		else {
			return filterShowFunction(functions, null);
		}
	}

	/**
	 * 过滤筛选
	 *
	 * @param all
	 * @param roleWith
	 * @return
	 */
	public List<OutTreeDTO> filterShowFunction(List<AppFunction> all, List<RoleFunction> roleWith) {
		List<OutTreeDTO> trees = new ArrayList<OutTreeDTO>();
		OutTreeDTO       obj1  = new OutTreeDTO();
		obj1.setId("0");
		obj1.setpId("");
		obj1.setName("所有功能");
		trees.add(obj1);

		if (roleWith != null && roleWith.size() > 0) {
			for (AppFunction appFunction : all) {
				if (appFunction.getStatus() == 0) {
					continue;//禁用的功能不展示
				}
				OutTreeDTO obj = new OutTreeDTO();
				obj.setId(appFunction.getId() + "");
				obj.setpId(appFunction.getParentcode());
				obj.setName(appFunction.getFunctionName());
				for (Iterator<RoleFunction> iterator = roleWith.iterator(); iterator.hasNext(); ) {
					RoleFunction rolefunction = iterator.next();
					if (String.valueOf(rolefunction.getFunction().getId()).equals(String.valueOf(appFunction.getId()))) {
						obj.setOperateStr(StringUtils.isEmpty(rolefunction.getOperateStr()) ? "" : rolefunction.getOperateStr());  //设置功能点操作权限
						obj.setChecked(true);
						break;
					} else {
						obj.setOperateStr("");  //设置功能点操作权限
					}
				}
				trees.add(obj);
			}
		} else {
			for (AppFunction appFunction : all) {
				if (appFunction.getStatus() == 0) {
					continue;//禁用的功能不展示
				}
				OutTreeDTO obj = new OutTreeDTO();
				obj.setId(appFunction.getId() + "");
				obj.setpId(appFunction.getParentcode());
				obj.setName(appFunction.getFunctionName());
				obj.setChecked(false);
				obj.setOperateStr("");
				trees.add(obj);
			}
		}
		return trees;
	}

	/**
	 * 系统功能树
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "functiontree", method = RequestMethod.POST, produces = "application/json")
	public @ResponseBody
	List<OutTreeDTO> queryFunctionTree(HttpServletRequest request,
									   HttpServletResponse response) {
		List<OutTreeDTO>  trees    = new ArrayList<OutTreeDTO>();
		List<AppFunction> funcList = functionManager.getAll();
		for (AppFunction appFunction : funcList) {
			OutTreeDTO obj = new OutTreeDTO();
			obj.setId(appFunction.getId().toString());//当前节点code
			obj.setName(appFunction.getFunctionName());//节点名称
			obj.setpId(appFunction.getParentcode());//父节点code
			obj.setOperateStr(appFunction.getUrl());
			//obj.setUrl(appFunction.getUrl());
			trees.add(obj);
		}

		return trees;
	}

	/**
	 * 菜单树
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "menutree", method = RequestMethod.POST, produces = "application/json")
	public @ResponseBody
	List<OutTreeDTO> queryMenuTree(HttpServletRequest request,
								   HttpServletResponse response) {
		List<AppMenu>    menuList = appMenuManager.getAll();
		List<OutTreeDTO> trees    = new ArrayList<OutTreeDTO>();
		for (AppMenu menu : menuList) {
			OutTreeDTO obj = new OutTreeDTO();
			obj.setId(menu.getTreeCode());      //当前节点code
			obj.setName(menu.getMenuName());    //节点名称
			obj.setpId(menu.getParentCode());   //父节点code
			trees.add(obj);
		}
		//根节点
		OutTreeDTO obj1 = new OutTreeDTO();
		obj1.setId("0");
		obj1.setName("系统菜单");
		obj1.setpId("-1");
		trees.add(obj1);
		return trees;
	}

	/**
	 * 新增（更新）菜单
	 */
	@RequestMapping(value = "addOrUpdateMenu", method = RequestMethod.POST, produces = "application/json")
	public @ResponseBody
	OutRetMsg addOrUpdateMenu(MultipartHttpServletRequest request,
							  HttpServletResponse response) {
		OutRetMsg outmsg  = new OutRetMsg();
		String    actType = request.getParameter("actType");
		try {
			//新增节点
			if ("add".equals(actType)) {
				AppMenu menu       = new AppMenu();
				String  treeCode   = request.getParameter("treeCode");
				String  parentCode = request.getParameter("parentCode");
				String  menuName   = request.getParameter("menuName");
				String  iconUrl    = request.getParameter("iconUrl");
				String  menuCode   = request.getParameter("menuCode");
				String  imagesUrl  = FileUploadUtils.getPicture(request);
				menu.setMenuIconUrl(imagesUrl);
				menu.setIconUrl(iconUrl);
				menu.setTreeCode(treeCode);
				menu.setParentCode(parentCode);
				menu.setMenuName(menuName);
				menu.setMenuCode(menuCode);
				menu.setCreateTime(new Date());
				appMenuManager.saveOrUpdate(menu);
				outmsg.setErrcode("200");
				outmsg.setErrmsg("success");
			} else if ("update".equals(actType)) {
				String  treeCode   = request.getParameter("treeCode");
				String  parentCode = request.getParameter("parentCode");
				AppMenu menu       = appMenuManager.getMenu(treeCode, parentCode);
				if (menu == null) {
					outmsg.setErrcode("201");
					outmsg.setErrmsg("not exit, update fail");
				} else {
					String  description = request.getParameter("description");
					String  ordernum    = request.getParameter("ordernum");
					String  menuName    = request.getParameter("menuName");
					Integer isApp       = Integer.parseInt(request.getParameter("isApp"));
					String  iconUrl     = request.getParameter("iconUrl");
					String  menuCode    = request.getParameter("menuCode");
					menu.setIconUrl(iconUrl);
					menu.setMenuCode(menuCode);
					menu.setMenuName(menuName == null ? menu.getMenuName() : menuName);
					menu.setDescription(description == null ? menu.getDescription() : description);
					menu.setIsApp(isApp);
					//menu.setOrdernum(ordernum==null?1:Integer.parseInt(ordernum.trim()));
					String imagesUrl = FileUploadUtils.getPicture(request);
					menu.setMenuIconUrl(imagesUrl);
					//关联功能点
					String funcId = request.getParameter("funcId");
					if (StringUtils.isNotEmpty(funcId)) {
						AppFunction function = functionManager.getById(Integer.parseInt(funcId));
						menu.setAppfunction(function);
					}
					appMenuManager.saveOrUpdate(menu);
					outmsg.setErrcode("200");
					outmsg.setErrmsg("success");
				}
			}
		} catch (Exception e) {
			outmsg.setErrcode("500");
			outmsg.setErrmsg("fail");
		}
		return outmsg;
	}

	/**
	 * 查询菜单基本信息
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "getMenu", method = RequestMethod.POST, produces = "application/json")
	public @ResponseBody
	MenuDto getMenu(HttpServletRequest request,
					HttpServletResponse response) {
		String  treeCode   = request.getParameter("treeCode");
		String  parentCode = request.getParameter("parentCode");
		AppMenu menu       = appMenuManager.getMenu(treeCode, parentCode);
		MenuDto dto        = new MenuDto(menu.getId(), menu.getMenuName(), treeCode, parentCode, menu.getDescription(), menu.getOrdernum(), menu.getIsApp());
		dto.setIconUrl(menu.getIconUrl());
		dto.setMenuCode(menu.getMenuCode());
		dto.setMenuIconUrl(menu.getMenuIconUrl());
		if (menu.getAppfunction() != null) {
			dto.setAppfunctionId(menu.getAppfunction().getId());
			dto.setUrl(menu.getAppfunction().getUrl());
		}
		return dto;
	}

	/**
	 * 删除菜单基本信息
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "deleMenu", method = RequestMethod.POST, produces = "application/json")
	public @ResponseBody
	OutRetMsg deleMenu(HttpServletRequest request,
					   HttpServletResponse response) {
		OutRetMsg outmsg     = new OutRetMsg();
		String    treeCode   = request.getParameter("treeCode");
		String    parentCode = request.getParameter("parentCode");
		appMenuManager.deleMenu(treeCode, parentCode);

		outmsg.setErrcode("200");
		outmsg.setErrmsg("success");
		return outmsg;
	}


	/**
	 * 查询用户系统菜单
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "loadMenuTree", method = RequestMethod.POST, produces = "application/json")
	public @ResponseBody
	List<OutTreeDTO> queryUserMenus(HttpServletRequest request,
									HttpServletResponse response) throws Exception {

		//用户功能操作权限session缓存，功能id:操作权限字符串
		Map<Integer, String> funcOperateCache = new HashMap<Integer, String>();
		//用户三级功能(按钮)操作权限字符串
		String perms = "";

		//获取当前用户
		User user = userManager.getUserByUsername2(request.getRemoteUser());
		//获取当前用户角色集合
		Set<Role> allRoleSet = user.getRoles();
		Set<Role> roleSet    = new HashSet<Role>();   //可用的角色
		Set<Long> roleIdSet  = new HashSet<Long>();   //可用的角色
		for (Role role : allRoleSet) {
			if (ElementConstant.YESORNO_1.equals(role.getIsenalbed())) {
				roleSet.add(role);
				roleIdSet.add(role.getId());
			}
			if (null != role.getId() && (1 == role.getId().intValue() || 2 == role.getId().intValue())) {
				Role roleSa = roleManager.get(new Long(-1));
				log.info("roleSa:" + roleSa);
				roleSet.add(roleSa);
				roleIdSet.add(roleSa.getId());
			}
		}

		//用户菜单集合
		List<AppMenu>    usermenus = new ArrayList<AppMenu>();
		List<OutTreeDTO> trees     = new ArrayList<OutTreeDTO>();
		if (roleSet != null && roleSet.size() > 0) {
			//获取系统菜单集合(所有)
			List<AppMenu> menus = appMenuManager.getAll2();
			//用户功能权限集合
			List<AppFunction> userfuncs = functionManager.getFunctionListByRole(roleIdSet);//用户功能权限集合 (去重以后的)

			//------------------- 原三级权限模块 可删除 -----------------------
			for (Role role : roleSet) {
				List<RoleFunction> funcSet = roleManager.queryRoleFunctionSet(role);
				for (RoleFunction roleFunction : funcSet) {
					AppFunction function = roleFunction.getFunction();
					funcOperateCache.put(function.getId(), roleFunction.getOperateStr());
				}
			}
			//-----------------------------------------------------

			if (userfuncs.size() > 0) {

				//拼接登录用户功能权限
				for (AppFunction appFunction : userfuncs) {
					if (StringUtils.isNotBlank(appFunction.getPerms())) {
						perms += appFunction.getPerms() + ",";
					}
				}

				//遍历系统菜单
				for (AppMenu appMenu : menus) {
					if (appMenu.getAppfunction() != null) {
						int functiondId = appMenu.getAppfunction().getId();
						for (AppFunction appFunction : userfuncs) {
							if (functiondId == appFunction.getId()) {
								AppFunction fun = functionManager.getById(functiondId);
								if (fun.getStatus() == 1) {
									usermenus.add(appMenu);
									break;
								}
							}
						}
					} else {
						//usermenus.add(appMenu);
					}
				}
			}
		}

		//用户Sesson缓存
		request.getSession().setAttribute("FunctionOperateCache", funcOperateCache);
		request.getSession().setAttribute("UserPerms", perms);//用户权限
		request.getSession().setAttribute("UserCache", user);
//		request.getSession().setAttribute("UserOrgRelationsCache", userManager.getUserOrgByUserId(user.getId().longValue()));
		request.getSession().setAttribute("orgs", appUserService.getUserOrgs(user.getId()));

		//组装数据方法
		for (AppMenu appMenu : usermenus) {
			OutTreeDTO obj = new OutTreeDTO();
			obj.setName(appMenu.getMenuName());
			obj.setId(appMenu.getTreeCode());
			obj.setpId(appMenu.getParentCode());
			obj.setUrl(appMenu.getAppfunction() == null ? "" : appMenu.getAppfunction().getUrl());
			//obj.setIcon("images/xt.png");
			trees.add(obj);
		}

		if (user.isAdmin()) {
			OutTreeDTO obj = new OutTreeDTO();
			obj.setName("权限设置测试");
			obj.setId("100");
			obj.setpId("3");
			obj.setUrl("admin/ajax/permTest");
			trees.add(obj);
		}
		return trees;
	}

	@RequestMapping("/permTest")
	public ModelAndView toPermTest() {
		return new ModelAndView("admin/permTest");
	}

	/**
	 * 查询用户系统菜单
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "loadRoleUser")
	public String loadRoleUser(HttpServletRequest request, HttpServletResponse response) {
		JSONObject json = new JSONObject();
		//获取当前用户
		User user = userManager.getUserByUsername2(request.getRemoteUser());
		//获取当前用户角色集合
		Set<Role> allRoleSet = user.getRoles();
		Set<Role> roleSet    = new HashSet<Role>();   //可用的角色
		long      userType   = 0;
		for (Role role : allRoleSet) {
			if (ElementConstant.YESORNO_1.equals(role.getIsenalbed())) {
				roleSet.add(role);
				userType = role.getId();
			}
		}

		List<OrgDto> dtos = appUserService.getUserOrgs(user.getId());
		json.put("passType", 0);
		if (dtos != null && dtos.size() >= 1) {
			
			if(dtos.size() > 1){
				json.put("passType", "2,3,4");
			}else if(dtos.size() ==1){
				TbOrganization org = organizationManager.getOrganizationById(dtos.get(0).getId());
				json.put("passType", org.getPassType());
			}
		}


		json.put("userType", userType);
		StringUtil.charSet(json, request, response);
		return null;
	}

	/**
	 * 查询维修类型
	 *
	 * @param request
	 * @param response
	 * @return 树
	 */
	@RequestMapping(value = "userRepairTypeTree", method = RequestMethod.GET, produces = "application/json")
	public @ResponseBody
	List<OutTreeDTO> queryUserRepairTypeTree(HttpServletRequest request,
											 HttpServletResponse response) {
		String        userid          = request.getParameter("userid");
		List<Element> repairTypeGroup = elementGroupManager.getElementsByGroupName("repairTypeGroup");
		;
		if (StringUtils.isNotEmpty(userid)) {
			User          user         = userManager.get(Long.parseLong(userid));
			List<Element> userTypeList = userRepairTypeManager.findByUser(Long.parseLong(userid));
			return filterShowRepairType(repairTypeGroup, userTypeList);
		} else {
			return filterShowRepairType(repairTypeGroup, null);
		}
	}

	public List<OutTreeDTO> filterShowRepairType(List<Element> all, List<Element> userWith) {
		String           pId   = "-10";
		List<OutTreeDTO> trees = new ArrayList<OutTreeDTO>();
		OutTreeDTO       obj1  = new OutTreeDTO();
		obj1.setId(pId);
		obj1.setpId("");
		obj1.setName("所有维修类型");
		trees.add(obj1);

		if (userWith != null && userWith.size() > 0) {
			for (Element role : all) {
				OutTreeDTO obj = new OutTreeDTO();
				obj.setId(role.getId().toString());
				obj.setpId(pId);
				obj.setName(role.getItemname());
				for (Element r : userWith) {
					if (r.getId().intValue() == role.getId().intValue()) {
						obj.setChecked(true);
						break;
					}
				}
				trees.add(obj);
			}
		} else {
			for (Element role : all) {
				OutTreeDTO obj = new OutTreeDTO();
				obj.setId(role.getId().toString());
				obj.setpId(pId);
				obj.setName(role.getItemname());
				obj.setChecked(false);
				trees.add(obj);
			}
		}
		return trees;
	}
}
