package com.palmnest.webapp.controller;

import com.palmnest.application.ElementConstant;
import com.palmnest.application.bean.AppResultDto;
import com.palmnest.application.bean.Pagenation;
import com.palmnest.application.core.util.AppResultUtil;
import com.palmnest.application.dto.OrgDto;
import com.palmnest.application.dto.WebPageResultDto;
import com.palmnest.model.AppFunction;
import com.palmnest.model.Role;
import com.palmnest.model.RoleFunction;
import com.palmnest.model.User;
import com.palmnest.service.AppFunctionManager;
import com.palmnest.service.AppUserService;
import com.palmnest.service.RoleManager;
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.ui.ExtendedModelMap;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * 系统角色控制器 Controller
 *
 * @author yb
 * @since 2014-05-29
 */
@Slf4j
@Controller
@RequestMapping("/admin/role/*")
public class AppRoleController extends BaseFormController {

	@Autowired
	private RoleManager           roleManager;
	@Autowired
	private AppFunctionManager    appFunctionManager;
	@Autowired
	private AppUserService        appUserService;
	@Autowired
	private UserRepairTypeManager userRepairTypeManager;

	// TODO 标记 现在还要走 setter 注入吗? 先看一下有没有问题
//	@Autowired
//	public void setRoleManager(RoleManager roleManager) {
//		this.roleManager = roleManager;
//	}
//	@Autowired
//	public void setAppFunctionManager(AppFunctionManager appFunctionManager) {
//		this.appFunctionManager = appFunctionManager;
//	}

	/**
	 * 跳转角色列表页面
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/list")
	public ModelAndView handleRequest(HttpServletRequest request,
									  HttpServletResponse response) throws Exception {
		initFunctionOperate(request);       //初始化功能操作权限
		User user = (User) request.getSession().getAttribute("UserCache");//----------联调时需放开注释

		Model  model = new ExtendedModelMap();
		String orgId = request.getParameter("orgId");

		List<OrgDto> dtos = appUserService.getUserOrgs(user.getId());
		model.addAttribute("orgs", dtos);
		model.addAttribute("orgId", orgId);
		return new ModelAndView("admin/roleList", model.asMap());
	}

	/**
	 * 获取角色列表
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "getRoleList")
	@ResponseBody
	public WebPageResultDto getRoleList(HttpServletRequest request, HttpServletResponse response) {

		User user = (User) request.getSession().getAttribute("UserCache");//----------联调时需放开注释

		//构建查询条件
		Map<String, String> criteria = new HashMap<String, String>();

		String orgId    = request.getParameter("orgId");
		String orgStr   = getUserManageOrgIds(user);
		String pageNo   = request.getParameter("pageNo");
		String pageSize = request.getParameter("pageSize");//每页显示数

		if (StringUtils.isEmpty(pageNo)) {
			pageNo = "1";
		}

		if (StringUtils.isEmpty(pageSize)) {
			pageSize = "10";
		}

		//根据项目过滤
		if (StringUtils.isNotBlank(orgId)) {
			orgStr = orgId;
		}

		//admin用户查询的话需要查询出超级管理员角色
		if (user.getUserType() == 1) {
			orgStr += ",-1";
		}

		criteria.put("orgStr", orgStr);

		try {
			Pagenation<Role> pagenation = roleManager.queryRole(Integer.parseInt(pageNo), Integer.parseInt(pageSize), criteria);

			WebPageResultDto dto = new WebPageResultDto("200", "成功", pagenation.getItems());
			dto.setCount((long) pagenation.getTotalCount());
			return dto;
		} catch (Exception e) {
			log.error("查询角色列表失败 getRoleList ===>" + e.getMessage());
		}

		return new WebPageResultDto("100", "查询角色列表失败", null);
	}

	/**
	 * 根据 SysCode 和 OrgId 查询角色列表
	 *
	 * @param orgId
	 * @return
	 */
	@RequestMapping(value = "/getRoleByOrgAndSysCode")
	@ResponseBody
	public AppResultDto getRoleByOrgAndSysCode(@RequestParam Integer orgId,@RequestParam Integer pageType,HttpServletRequest request) {

		try {
			User user = (User) request.getSession().getAttribute("UserCache");
			List<OrgDto> organizationList = appUserService.getUserOrgs(user.getId());
			if (organizationList.size() >= 1) {
				orgId = organizationList.get(0).getId();
			}
			if(null == pageType){//pageType 1-物品放行 2-空调加时 
				pageType = 1;//
			}
			return AppResultUtil.createSuccesDto(roleManager.getRoleByOrgAndSysCode(orgId,pageType));
		} catch (Exception e) {
			log.error("查询角色列表失败 getRoleByOrgAndSysCode ===>" + e.getMessage(), e);
		}

		return AppResultUtil.createErrorDto("100", "查询角色列表失败");
	}

	/**
	 * 角色新增或者更新
	 *
	 * @param role
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/form")
	public ModelAndView formRequest(@ModelAttribute("role") Role role, HttpServletRequest request) throws Exception {

		Model model = new ExtendedModelMap();

		User user = (User) request.getSession().getAttribute("UserCache");

		List<OrgDto> dtos = appUserService.getUserOrgs(user.getId());

		model.addAttribute("orgs", dtos);

		String actType = request.getParameter("actType");
		String orgId   = request.getParameter("orgId");

		model.addAttribute("orgId", orgId);

		if ("save".equals(actType)) {

			if (StringUtils.isNotEmpty(role.getSYSCODE())) {

				String code = role.getSYSCODE();
				String id   = "";

				if (role.getId() != null) {
					id = role.getId().toString();
				}

				List<Role> list = roleManager.getRoleListBySysCode(id, code);

				if (list != null && list.size() > 0) {
					model.addAttribute("errormsg", "系统编码不能重复");
					model.addAttribute("funcid", request.getParameter("funcid"));
					return new ModelAndView("admin/roleForm", model.asMap());
				}

			}

			Role r = null;

			long roleid = 0;
			int  num    = 0;

			if (role.getId() != null) {

				roleid = role.getId().longValue();
				r = roleManager.get(role.getId());
				r.setName(role.getName());
				r.setDescription(role.getDescription());
				//r.setRoleType(0);

				if (r.getFLOOR_REPAIR() != role.getFLOOR_REPAIR()) {
					num = 1;
				}

				r.setFLOOR_REPAIR(role.getFLOOR_REPAIR());
				r.setStatusFlag(1);
				r.setLastUpdatedTime(new Date());
				r.setISINITIALIZATION(role.getISINITIALIZATION());
				r.setSYSCODE(role.getSYSCODE());

				roleManager.updateObj(r);

				model.addAttribute("errormsg", "更新成功");

			} else {

				role.setRoleType(4);
				role.setStatusFlag(1);
				role.setIsenalbed(ElementConstant.YESORNO_1);
				role.setLastUpdatedTime(new Date());

				roleManager.saveObj(role);

				r = role;

				roleid = role.getId().longValue();

				model.addAttribute("errormsg", "新增成功");
			}

			if (0 != roleid && num == 1) {
				userRepairTypeManager.removeByRoleId(roleid);
			}

			// 删除角色的功能点，重新保存
			roleManager.deleteRoleFunctions(roleid);

			String funcIds = request.getParameter("funcIds");

			if (StringUtils.isNotEmpty(funcIds)) {

				String[] ids = funcIds.split(";");

				for (String tempid_ : ids) {

//					String[] tempid=tempid_.split(":");

					RoleFunction rolefunction = new RoleFunction();

//					if(tempid.length>1){
//						rolefunction.setOperateStr(tempid[1]);    //操作权限，1-新增 2-修改 3-删除
//					}

					AppFunction byId = appFunctionManager.getById(Integer.parseInt(tempid_));

					if (byId != null) {
						rolefunction.setFunction(byId);
						rolefunction.setRole(r);
						roleManager.saveRoleFunction(rolefunction);
					}
				}
			}

			model.addAttribute(role);
		}

		model.addAttribute("funcid", request.getParameter("funcid"));
		model.addAttribute("id", role.getId());

		return new ModelAndView("admin/roleForm", model.asMap());
	}

	/**
	 * 编辑页面
	 * eg : view-source:http://wx.palmnest.com/super_service/admin/role/update/-1&7
	 *
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/update/{id}&{funcid}")
	public String update(@PathVariable long id, @PathVariable long funcid, Model model, HttpServletRequest request) {

		model.addAttribute(roleManager.get(id));
		Role role = roleManager.get(id);

		model.addAttribute("funcid", funcid);

		// 当前项目
		model.addAttribute("orgId", role.getOrgId());

		User user = (User) request.getSession().getAttribute("UserCache");

		List<OrgDto> dtos = appUserService.getUserOrgs(user.getId());

		// 选择项目
		model.addAttribute("orgs", dtos);

		return "admin/roleForm";
	}

	/**
	 * 删除角色
	 *
	 * @param id 角色id
	 * @return
	 */
	@RequestMapping(value = "/delete/{id}&{funcid}")
	public String delete(@PathVariable long id, @PathVariable long funcid) {
		Role role = roleManager.get(id);
		if (role.getISINITIALIZATION() == 0) {
			role.setIsenalbed(ElementConstant.YESORNO_0);
			roleManager.save(role);
		}

		return "redirect:/admin/role/list?funcid=" + funcid;
	}

	@RequestMapping(value = "/info/{id}&{funcid}")
	public String redirect(@PathVariable long id, @PathVariable long funcid, Model model) {
		model.addAttribute("model", roleManager.get(id));
		model.addAttribute("funcid", funcid);
		return "admin/roleInfo";
	}


	//TODO TEST
	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public String add(@ModelAttribute("role") Role role) {
		return "admin/add";
	}

	//TODO TEST
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public String add(Role role, String oo) {
		return "redirect:/admin/role/list";
	}

	//TODO TEST
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	public String show(@PathVariable long id) {
		return "admin/show";
	}

}
