package com.ssm.controller.system;

import java.util.ArrayList;
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.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.DataBinder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
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.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.ssm.model.system.SysDepartment;
import com.ssm.model.system.SysUser;
import com.ssm.model.validator.DepartmentValidator;
import com.ssm.service.system.SysDepartmentService;
import com.ssm.service.system.SysPositionService;
import com.ssm.util.PackageBeanUtils;
import com.ssm.util.Util;
import com.ssm.util.page.PagedResult;
import com.ssm.web.Const;
import com.ssm.web.RoleLimit;

/**
 * 部门管理
 * */
@RequestMapping("sysDepartment")
@Controller
public class DepartmentController{
	
	@Autowired
	private SysDepartmentService sysDepartmentService;
	
	@Autowired
	private SysPositionService sysPositionService;
	
	/**
	 * 部门分页查询
	 * */
	@RequestMapping(value="getDepartmentList")
	@ResponseBody
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID, mid = Const.SYSTEM_ROLE_LIMIT_MID)
	public ModelAndView getDepartmentList(SysDepartment sysDepartment,Integer pageNo,Integer pageSize){
	
		ModelAndView view=new ModelAndView("sysdepartment/departmentList");
		
		PagedResult<SysDepartment> pagedResult=sysDepartmentService.sysDepartmentQuery(sysDepartment, pageNo, pageSize);

		view.addObject("list", pagedResult);
		
		//部门
		List<SysDepartment> sysDepartmentlist=sysDepartmentService.getDepartmentList();
		List<SysDepartment> parenpagelist = new ArrayList<SysDepartment>();
		
		
		if(null != sysDepartmentlist && sysDepartmentlist.size() > 0){
			
			//封装一级菜单
			for (SysDepartment sysDepartment2 : sysDepartmentlist) {
				if(sysDepartment2.getLevel()==1){
					parenpagelist.add(sysDepartment2);
				}
			}
			
			if(null != parenpagelist && parenpagelist.size() > 0){
				
				//一级菜单的每个对象和所以的菜单比较
				for (int i = 0; i < parenpagelist.size(); i++) {
					
					System.out.println("***************"+i);
					PackageBeanUtils.packageParentDepartmentlist(parenpagelist.get(i) , sysDepartmentlist);
					
				}
			}
		}
		
		
		System.out.println(JSON.toJSON(parenpagelist));
		
		view.addObject("sysDepartmentlist", parenpagelist);
		
		return view;
	}
	/**
	 * 
	 * 删除部门
	 * */
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID, mid = Const.SYSTEM_ROLE_LIMIT_MID)
	@RequestMapping(value="getDeleteDepartment",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> getDeleteDepartment(HttpServletRequest request,HttpSession session){
		
		SysDepartment department=new SysDepartment();
		
		Map<String, Object> record = new HashMap<String, Object>();
		record.put("success", true);
		
		String depid = request.getParameter("depid");
	
		//查询该部门下是否有职位
		int count=sysPositionService.QuerySysPostionId(Integer.parseInt(depid));
		
		if(count>0){
			record.put("pm", false);
			return record;
		}else{
			//可删除
			SysUser operator = Util.getUserSession(request);
			department.setLastupdatedatetime(new Date());
			department.setLastupdateuserid(operator.getUserid());
			department.setIsdeleted(true);//0可选(false)
			department.setDepid(Integer.parseInt(depid));
			sysDepartmentService.updateByPrimaryKeySelective(department);
			record.put("success", true);
		}
		
		return record;
	}
	
	
	
	/**
	 * 部门管理表单提交 绑定验证
	 * @param binder
	 */
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID, mid = Const.SYSTEM_ROLE_LIMIT_MID)
	@InitBinder("sysDepartment")
	public void InitBinder(DataBinder binder){
		binder.setValidator(new DepartmentValidator());
	}
	
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID, mid = Const.SYSTEM_ROLE_LIMIT_MID)
	@RequestMapping(value="getVerification")
	@ResponseBody
	public ModelAndView getVerification(){
		ModelAndView view=new ModelAndView("sysdepartment/departmentAdd");	
		view.addObject("sysDepartment", new SysDepartment());
		
		//部门
		List<SysDepartment> sysDepartmentlist=sysDepartmentService.getDepartmentList();
		List<SysDepartment> parenpagelist = new ArrayList<SysDepartment>();
		
		
		if(null != sysDepartmentlist && sysDepartmentlist.size() > 0){
			
			//封装一级菜单
			for (SysDepartment sysDepartment2 : sysDepartmentlist) {
				if(sysDepartment2.getLevel()==1){
					parenpagelist.add(sysDepartment2);
				}
			}
			
			if(null != parenpagelist && parenpagelist.size() > 0){
				
				//一级菜单的每个对象和所以的菜单比较
				for (int i = 0; i < parenpagelist.size(); i++) {
					
					System.out.println("***************"+i);
					PackageBeanUtils.packageParentDepartmentlist(parenpagelist.get(i) , sysDepartmentlist);
					
				}
			}
		}
		
		
		System.out.println(JSON.toJSON(parenpagelist));
		
		view.addObject("sysDepartmentlist", parenpagelist);
		return view;
	}
	
	/**
	 * 新增部门
	 * 
	 * */
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID, mid = Const.SYSTEM_ROLE_LIMIT_MID)
	@RequestMapping(value="getAddSysdepartment")
	public String getAddSysdepartment(HttpServletRequest request, @Validated @ModelAttribute("sysDepartment") SysDepartment sysDepartment,
			BindingResult result,HttpSession session){
		
	 if(result.hasErrors()==false){
			int count=sysDepartmentService.countByExample();
			SysUser operator = Util.getUserSession(request);
			sysDepartment.setCreateduserid(operator.getUserid());//创建人id
			sysDepartment.setCreateddatetime(new Date());//创建时间
			sysDepartment.setDeptrolecode(String.valueOf(count+1));//序号
			sysDepartment.setIsdeleted(false);//0是false,1是true
			
			Integer parentid = sysDepartment.getParentid();
			if(null == parentid){
				sysDepartment.setParentid(-1);
				parentid = -1;
			}
			//根据departmentid查询
			SysDepartment sp= sysDepartmentService.sysDepartmentParentid(parentid);
			
			if(null == sp){
				sysDepartment.setLevel(1);
			}else{
				sysDepartment.setLevel(sp.getLevel()+1);
			}
			
			//根据parentid查询
			Integer count2=sysDepartmentService.selectParentid(parentid);
			if(0 == count2){
				if(null == sp){
					
					sysDepartment.setDepartmentid(1);
				}else{
					sysDepartment.setDepartmentid(sp.getDepartmentid()*1000 +1);
				}
			}else{
				Integer  maxMenuid = sysDepartmentService.selectMaxParentid(parentid);
				sysDepartment.setDepartmentid(maxMenuid + 1);
			}
			
			sysDepartmentService.insertSelective(sysDepartment);
			return "redirect:getDepartmentList";
		 }
		return "sysdepartment/departmentAdd";
	}
	
	/**
	 * 编辑部门
	 * */
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID, mid = Const.SYSTEM_ROLE_LIMIT_MID)
	@RequestMapping(value="getSelectdepartment")
	@ResponseBody
	public ModelAndView getSelectdepartment(Integer depid){
		ModelAndView view=new ModelAndView("sysdepartment/departmentUpdate");
		SysDepartment  sd=sysDepartmentService.selectByPrimaryKey(depid);
		view.addObject("sd",sd);
		view.addObject("sysDepartment", new SysDepartment());
		//部门层级
		List<SysDepartment> sysDepartmentlist=sysDepartmentService.getDepartmentList();
		List<SysDepartment> parenpagelist = new ArrayList<SysDepartment>();
		
		if(null != sysDepartmentlist && sysDepartmentlist.size() > 0){
			
			//封装一级菜单
			for (SysDepartment sysDepartment2 : sysDepartmentlist) {
				if(sysDepartment2.getLevel()==1){
					parenpagelist.add(sysDepartment2);
				}
			}
			
			if(null != parenpagelist && parenpagelist.size() > 0){
				
				//一级菜单的每个对象和所以的菜单比较
				for (int i = 0; i < parenpagelist.size(); i++) {
					
					PackageBeanUtils.packageParentDepartmentlist(parenpagelist.get(i) , sysDepartmentlist);
					
				}
			}
		}
		
		view.addObject("sysDepartmentlist", parenpagelist);
		
		return view;
	}
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID, mid = Const.SYSTEM_ROLE_LIMIT_MID)
	@RequestMapping(value="getUpdateSysdepartment",method=RequestMethod.POST)
	public String getUpdateSysdepartment(HttpServletRequest request, HttpSession session,@Validated @ModelAttribute("sysDepartment")SysDepartment sysDepartment,BindingResult result){
		
		
		if(result.hasErrors()==false){
			SysUser operator = Util.getUserSession(request);
			sysDepartment.setLastupdateuserid(operator.getUserid());//更新人id
			sysDepartment.setLastupdatedatetime(new Date());//更新时间
			
			sysDepartmentService.updateByPrimaryKeySelective(sysDepartment);
			return "redirect:getDepartmentList";
		}

		return "sysdepartment/departmentUpdate";
	}
}
