package com.blueland.bpm.manage.web;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import org.activiti.engine.impl.RepositoryServiceImpl;
import org.activiti.engine.impl.pvm.PvmActivity;
import org.activiti.engine.impl.pvm.ReadOnlyProcessDefinition;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.blueland.bpm.application.model.ApplicationEntity;
import com.blueland.bpm.application.service.ApplicationManager;
import com.blueland.bpm.common.base.BaseSpringController;
import com.blueland.bpm.common.page.Page;
import com.blueland.bpm.engine.config.model.Role;
import com.blueland.bpm.engine.config.model.User2role;
import com.blueland.bpm.engine.config.service.RoleManager;
import com.blueland.bpm.engine.core.model.ProcessDefinitionModel;
import com.blueland.bpm.engine.core.model.SearchProcessListDTO;
import com.blueland.bpm.engine.core.service.ProcessDefinitionService;
import com.blueland.bpm.engine.util.ProcessDefinitionUtils;
import com.blueland.bpm.identity.OrgService;
import com.blueland.bpm.identity.UserService;
import com.blueland.bpm.identity.model.Org;
import com.blueland.bpm.identity.model.User;
import com.blueland.bpm.manage.util.BaseUser;
import com.blueland.bpm.manage.util.MyContants;
import com.blueland.bpm.manage.util.XLSExportUtil;

@Controller
@RequestMapping(value = "role")
public class RoleController extends BaseSpringController{
	//默认多列排序,example: username desc,createTime asc
	protected static final String DEFAULT_SORT_COLUMNS = "roleSort"; 
	
	private final String LIST_ACTION = "redirect:/role/list.do";
	
	@Autowired
	private RoleManager roleManager;
	@Autowired
	private UserService userService;
	@Autowired
	private OrgService orgService;
	@Autowired
	private ApplicationManager applicationService;
	@Autowired
	private ProcessDefinitionService processDefinitionService;
	
	public RoleController(){
		
	}
	
	/** 
	 * 执行搜索 
	 * @throws Exception
	 **/
	@RequestMapping(value = "list")
	public ModelAndView list(HttpServletRequest request,Role query) throws Exception {
		String loginUserAppId = BaseUser.getInstance().getLoginUserAppId(request);
		ApplicationEntity applicaton =  applicationService.getById(loginUserAppId);
		
		//设置当前登录用户id以便查询
		User loginUser = BaseUser.getInstance().getSessionUser(request);
		if(BaseUser.isEbpmAdminSession(request)) {
			query.setRoleOrgId("admin");
		}
		query.setRoleAppId(applicaton.getAppId());
		Page page = this.roleManager.findPage(query);
		ModelAndView result = new ModelAndView("/role/list");
		result.addAllObjects(toModelMap(page, query));

		result.addObject("applicaton", applicaton);
		result.addObject("loginUser", loginUser);
		return result;
	}
	
	

	/** 
	 * 进入新增或者编辑页面
	 **/
	@RequestMapping(value = "create")
	public ModelAndView create(HttpServletRequest request,Role role)  {
		String loginUserAppId = BaseUser.getInstance().getLoginUserAppId(request);
		ApplicationEntity applicaton =  applicationService.getById(loginUserAppId);
		ModelAndView result = new ModelAndView("/role/create");
		result.addObject("role", role);
		result.addObject("applicaton", applicaton);
		return result;
	}
	
	
	
	/** 
	 * 进入新增页面
	 **/
	@RequestMapping(value = "edit")
	public ModelAndView edit(HttpServletRequest request,Role role)  {
		String loginUserAppId = BaseUser.getInstance().getLoginUserAppId(request);
		ApplicationEntity applicaton =  applicationService.getById(loginUserAppId);		
		ModelAndView result = new ModelAndView("/role/edit");		
		Role tempRole = roleManager.selectByRoleId(role.getRoleId());
		result.addObject("role", tempRole);
		result.addObject("applicaton", applicaton);
		return result;
	}
	
	/**
	 * 新增之后保存对象
	 * @throws Exception 
	 **/
	@RequestMapping(value = "save")
	@ResponseBody
	public String save(HttpServletRequest request,Role role,RedirectAttributes redirectAttributes) throws Exception  {
		User loginUser = BaseUser.getInstance().getSessionUser(request);
		role.setRoleCreator(loginUser.getUserId());	
		String messageInfo = ACTION_SUCCESS;
		if(null!=role && null!=role.getRoleId() && !"".equals(role.getRoleId())){
			Role tempRole = roleManager.selectByRoleId(role.getRoleId());
			if(tempRole != null){
				messageInfo =  "["+role.getRoleAppId()+"]"+"应用系统已存在角色编码为["+role.getRoleId()+"]的角色，请您重新输入角色编码！";				
			}
		}
		roleManager.saveRole(role);
		return messageInfo;
	}

	
	/**
	 * 保存对象
	 * @throws Exception 
	 **/
	@RequestMapping(value = "update")
	@ResponseBody
	public String update(HttpServletRequest request,Role role) throws Exception  {
		User loginUser = BaseUser.getInstance().getSessionUser(request);
		role.setRoleCreator(loginUser.getUserId());
		roleManager.saveRole(role);
		return ACTION_SUCCESS;
	}
	
	
	
	/**
	 * 保存对象
	 **/
	@RequestMapping(value = "saveUser2role")
	@ResponseBody
	public String saveUser2role(HttpServletRequest request,String userIds,String roleId)  {
		MyContants.saveUserOperate(request, "roleId;userIds", true,"角色人员变更成功",
				MyContants.LOGIN_SESSION_USER,MyContants.APPLICATION);
		roleManager.saveUser2role(userIds, roleId);
		return ACTION_SUCCESS;
	}
	
	/**
	 * 保存对象
	 **/
	@RequestMapping(value = "delete")
	@ResponseBody
	public ModelAndView delete(HttpServletRequest request,RedirectAttributes redirectAttributes)  {
		String roleId = request.getParameter("item");
		//通过roleId得到role对象，从而得到AppId（系统Id）
		Role role =roleManager.selectByRoleId(roleId);
		String appId = role.getRoleAppId();
		//资源类型：分为三种（角色role、组织org、人员user）
		String resourceType = "role";
		//map返回结果,tenantId、procDefId、procDefName、activityId、activityName
		List<Map<String,String>> inProcess =null;
		try{
			inProcess = processDefinitionService.findProcessDefsByResource(appId,"",resourceType,roleId);
		}catch(Exception e){
			e.printStackTrace();
		}
		if(inProcess!=null&&inProcess.size()>0){
			redirectAttributes.addFlashAttribute(ACTION_MESSAGE, "该角色已绑定在流程环节中，无法删除！");
		}else{
			roleManager.deleteBatch(roleId);
			redirectAttributes.addFlashAttribute(ACTION_MESSAGE, DELETE_SUCCESS);
			MyContants.saveUserOperate(request, "items", true, "删除成功",
					MyContants.LOGIN_SESSION_USER,MyContants.APPLICATION);
		}

		return new ModelAndView(LIST_ACTION);
	}
	
	/**
	 * 根据roleIds获取相对应的user对象
	 * @param request
	 * @return
	 */
	@RequestMapping(value="queryUserByRoleIdsAjax")
	@ResponseBody
	public List<User> queryUserByRoleIdsAjax(HttpServletRequest request,String roleId){
		
		List<User> users = new ArrayList<User>();
		
		List<User2role> list = roleManager.getUser2roleList(roleId);
		if(!list.isEmpty()){
			for (User2role user2role : list) {
				User user = userService.getUserById(user2role.getUserId());
				if(null!=user){
					user.setOrgId(user2role.getOrgName());
					users.add(user);
				}else{
					System.out.println(user2role.getUserId());
				}
			
			}
		}
		return  users;
	}
	
	
	
	/**
	 * 导出 流程清单 excel
	 * 
	 * 
	 */
	@RequestMapping(value = "/export")
	public void export(HttpServletRequest request, HttpServletResponse response) {
		SearchProcessListDTO params = new SearchProcessListDTO();
		params.setTenantId(BaseUser.getInstance().getLoginUserAppId(request));
		String url = request.getServletContext().getRealPath("/");
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		String exls = url + "/file/";
		String name = "角色清单" + "_" + df.format(new Date()) + ".xls";
		String path = exls.replace("/", File.separator);
		File file = new File(exls);
		if (!file.exists()) {
			file.mkdirs();
		}
		XLSExportUtil exportUtil = new XLSExportUtil(name, path);
		exportUtil.removeSheetAt(0);
		String[] sheet1 = { "角色编码", "角色名称", "成员ID", "成员名称", "成员组织ID", "成员组织名称" };
		// 第一个sheet
		roleSheet(exportUtil, "角色列表", sheet1, params);
		response.setContentType("application/vnd.ms-excel");
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			exportUtil.exportXLS();
			response.setHeader("Content-disposition",
					"attachment;filename=" + new String(name.getBytes(), "iso-8859-1"));

			FileInputStream is = new FileInputStream(exls + name);
			ServletOutputStream out = response.getOutputStream();
			bis = new BufferedInputStream(is);
			bos = new BufferedOutputStream(out);
			byte[] buff = new byte[2048];
			int bytesRead;
			// Simple read/write loop.
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
			bis.close();
			bos.close();
		} catch (Exception e) {

			e.printStackTrace();
		}

	}
	
	
	public void roleSheet(XLSExportUtil exportUtil,String sheetName,String[] titles,SearchProcessListDTO params){
		int rowNum = 0;								//行数
		int cellNum = 0;							//列数
		exportUtil.createSheet(sheetName);			//新增sheet设置名称
		exportUtil.createRow(rowNum++);				//在sheet中新增一行、展示查询数据——标题
		for (String title : titles) {
			exportUtil.setCell(cellNum++, title);
		}
		Role prole=new Role();
		prole.setRoleAppId(params.getTenantId());
		List<Role> roles=this.roleManager.findRolesByParam(prole);
		for (Role role : roles) {
			List<User2role> user2roles=this.roleManager.getUser2roleList(role.getRoleId());
			if(user2roles.isEmpty()) {
				exportUtil.createRow(rowNum++);	
				exportUtil.setCell(0,role.getRoleId());
				exportUtil.setCell(1,role.getRoleName());
				exportUtil.setCell(2,"");
				exportUtil.setCell(3,"");
				exportUtil.setCell(4,"");
				exportUtil.setCell(5,"");
			}
			for (User2role user2role : user2roles) {
				exportUtil.createRow(rowNum++);	
				exportUtil.setCell(0,role.getRoleId());
				exportUtil.setCell(1,role.getRoleName());
				exportUtil.setCell(2,user2role.getUserCode());
				exportUtil.setCell(3,user2role.getUserName());
				exportUtil.setCell(4,user2role.getOrgId());
				exportUtil.setCell(5,user2role.getOrgName());
			}
		}
	}
	/**
	 * 新增之后保存对象
	 * @throws Exception 
	 **/
	@RequestMapping(value = "sync/saveOrUpdate")
	@ResponseBody
	public String syncSave(HttpServletRequest request,@RequestBody Map<String,Object> params){
		Role role = new Role();
		role.setRoleId(params.get("roleId") != null ? params.get("roleId").toString():"");
		role.setRoleAppId(params.get("roleAppId") != null ? params.get("roleAppId").toString():"");
		role.setRoleName(params.get("roleName")!= null ? params.get("roleName").toString():"");
		role.setRoleSort(params.get("roleSort")!= null ? Integer.parseInt(params.get("roleSort").toString()):null);
		role.setRoleType(params.get("roleType")!= null ? params.get("roleType").toString():"");
		role.setRoleAppName(params.get("appName")!= null ? params.get("appName").toString():"");
		role.setRoleStatus(params.get("roleStatus")!= null? params.get("roleStatus").toString():"");
		role.setRemark(params.get("remark")!= null? params.get("remark").toString():"");
		role.setRoleCreator(params.get("userId")!= null? params.get("userId").toString():"");	
		roleManager.saveRole(role);
		return ACTION_SUCCESS;
	}
	/**
	 * 保存角色用户
	 **/
	@RequestMapping(value = "sync/saveUserrole")
	@ResponseBody
	public String syncSaveUserrole(HttpServletRequest request,@RequestBody Map<String,Object> params)  {
		MyContants.saveUserOperate(request, "roleId;userIds", true,"角色人员变更成功",
				MyContants.LOGIN_SESSION_USER,MyContants.APPLICATION);
		roleManager.saveUser2role(params.get("userIds").toString(), params.get("roleId").toString());
		return ACTION_SUCCESS;
	}
	/**
	 * 删除角色
	 **/
	@RequestMapping(value = "sync/delRole")
	@ResponseBody
	public Map<String,Object> delRole(HttpServletRequest request,@RequestBody Map<String,Object> params)  {
		Map<String,Object> result = new HashMap<String, Object>();
		boolean flag = false;
		String msg = "角色id不能为空！";
		if(params.get("roleId") == null){
			result.put("flag", flag);
			result.put("msg", msg);
			return result;
		}
		String roleId = params.get("roleId").toString();
		//通过roleId得到role对象，从而得到AppId（系统Id）
		Role role =roleManager.selectByRoleId(roleId);
		String appId = role.getRoleAppId();
		//资源类型：分为三种（角色role、组织org、人员user）
		String resourceType = "role";
		//map返回结果,tenantId、procDefId、procDefName、activityId、activityName
		List<Map<String,String>> inProcess =null;
		try{
			inProcess = processDefinitionService.findProcessDefsByResource(appId,"",resourceType,roleId);
		}catch(Exception e){
			e.printStackTrace();
		}
		if(inProcess!=null&&inProcess.size()>0){
			msg = "该角色已绑定在流程环节中，无法删除！";
		}else{
			roleManager.deleteBatch(roleId);
			flag = true;
			msg = "删除成功";
		}
		result.put("flag", flag);
		result.put("msg", msg);
		return result;
	}
}
