/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.workfullmeetingminutes.web;

import com.google.common.collect.Lists;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.MyBeanUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.modules.act.entity.Act;
import com.jeeplus.modules.act.service.ActTaskService;
import com.jeeplus.modules.act.utils.ActUtils;
import com.jeeplus.modules.sys.entity.Office;
import com.jeeplus.modules.sys.entity.Role;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.service.OfficeService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workactivity.entity.Activity;
import com.jeeplus.modules.workactivity.service.ActivityService;
import com.jeeplus.modules.workfullmanage.entity.WorkFullManage;
import com.jeeplus.modules.workfullmanage.service.WorkFullManageService;
import com.jeeplus.modules.workfullmeetingminutes.entity.WorkFullMeetingminutes;
import com.jeeplus.modules.workfullmeetingminutes.service.WorkFullMeetingminutesService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 会议纪要Controller
 * @author fgy
 * @version 2017-11-02
 */
@SuppressWarnings("all")
@Controller
@RequestMapping(value = "${adminPath}/workfullmeetingminutes/workFullMeetingminutes")
public class WorkFullMeetingminutesController extends BaseController {

	@Autowired
	private WorkFullManageService workFullManageService;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private ActTaskService actTaskService;
	@Autowired
	private WorkFullMeetingminutesService workFullMeetingminutesService;
	@Autowired
	private ActivityService activityService;

	@ModelAttribute
	public WorkFullMeetingminutes get(@RequestParam(required=false) String id) {
		WorkFullMeetingminutes entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workFullMeetingminutesService.get(id);
		}
		if (entity == null){
			entity = new WorkFullMeetingminutes();
		}
		return entity;
	}

	/**
	 * 待添加会议纪要的项目列表
	 */
	@RequiresPermissions("workfullmeetingminutes:workFullMeetingminutes:workfullmanageList")
	@RequestMapping("/workfullmanageList")
	public String workfullmanageList(WorkFullManage workFullManage , HttpServletRequest request, HttpServletResponse response, Model model){
		String userId = UserUtils.getUser().getId();
		//仅是普通员工
		if(!UserUtils.getSelectRoleInfo()){
			workFullManage.setQueryCon(userId);
		}

		Page<WorkFullManage> page = workFullMeetingminutesService.findListOfWorkFullManage(new Page<WorkFullManage>(request, response), workFullManage);
		model.addAttribute("page", page);
		return "modules/workfullmeetingminutes/workfullmanageList";
	}
	
	/**
	 * 会议纪要列表页面
	 */
	@RequiresPermissions("workfullmeetingminutes:workFullMeetingminutes:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkFullMeetingminutes workFullMeetingminutes, HttpServletRequest request, HttpServletResponse response, Model model) {
		String workFullManageId = request.getParameter("workFullManageId");

		if(StringUtils.isNotBlank(workFullManageId)){
			workFullMeetingminutes.setWorkFullManageId(workFullManageId);
		}
		Page<WorkFullMeetingminutes> page = workFullMeetingminutesService.findPage(new Page<WorkFullMeetingminutes>(request, response), workFullMeetingminutes);
		model.addAttribute("page", page);
		model.addAttribute("workFullManage",workFullManageService.get(workFullManageId));
		model.addAttribute("workFullManageId",workFullManageId);

		return "modules/workfullmeetingminutes/workFullMeetingminutesList";
	}

	/**
	 * 查看，增加，编辑会议纪要表单页面
	 */
	@RequiresPermissions(value={"workfullmeetingminutes:workFullMeetingminutes:view","workfullmeetingminutes:workFullMeetingminutes:add","workfullmeetingminutes:workFullMeetingminutes:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkFullMeetingminutes workFullMeetingminutes, Model model,HttpServletRequest request) {
		String dialog = request.getParameter("dialog");
		String workFullManageId = request.getParameter("workFullManageId");
		String listpage = request.getParameter("listpage");
		if(StringUtils.isBlank(workFullManageId)){
			workFullManageId = workFullMeetingminutes.getWorkFullManageId();
		}
		model.addAttribute("workFullMeetingminutes", workFullMeetingminutes);
		model.addAttribute("listpage",listpage);

		if(workFullMeetingminutes.getAct()!=null && StringUtils.isNotBlank(workFullMeetingminutes.getAct().getTaskId())){
			String taskId = workFullMeetingminutes.getAct().getTaskId();
			return "modules/workfullmeetingminutes/workFullMeetingminutesAudit";
		}

		if("add".equals(dialog) || "edit".equals(dialog)){
			return "modules/workfullmeetingminutes/workFullMeetingminutesForm";
		}
		if("view".equals(dialog)){
			return "modules/workfullmeetingminutes/workFullMeetingminutesView";
		}
		return "modules/workfullmeetingminutes/workFullMeetingminutesForm";
	}

	/**
	 * 保存会议纪要
	 */
	@RequiresPermissions(value={"workfullmeetingminutes:workFullMeetingminutes:add","workfullmeetingminutes:workFullMeetingminutes:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(WorkFullMeetingminutes workFullMeetingminutes, Model model,HttpServletRequest request,@RequestParam(value = "listpage",required = false)String listpage,RedirectAttributes redirectAttributes) throws Exception{
		//新添加（submit提交，toStore暂存），被驳回（reapply重新申请，repeal撤销）
		String submit = request.getParameter("submit");
		String workFullManageId = request.getParameter("workFullManageId");
		if (!beanValidator(model, workFullMeetingminutes)){
			return form(workFullMeetingminutes, model,null);
		}
		if(!workFullMeetingminutes.getIsNewRecord()){//编辑表单保存
			WorkFullMeetingminutes t = workFullMeetingminutesService.get(workFullMeetingminutes.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workFullMeetingminutes, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			//被驳回状态
			if (StringUtils.isNotBlank(t.getStatus()) &&t.getStatus().equals("3")){
				ProcessInstance processInstance = actTaskService.getProcIns(t.getProcessInstanceId());
				if (processInstance!=null) {
					Task taskInfok = actTaskService.getCurrentTaskInfo(processInstance);
					Act act = new Act();
					act.setTaskId(taskInfok.getId());
					act.setTaskName(taskInfok.getName());
					act.setTaskDefKey(taskInfok.getTaskDefinitionKey());
					act.setProcDefId(taskInfok.getProcessDefinitionId());
					act.setProcInsId(taskInfok.getProcessInstanceId());
					act.setTask(taskInfok);
					if("reapply".equals(submit)){act.setFlag("yes");}//重新申请
					if("repeal".equals(submit)){act.setFlag("no");}//撤销
					t.setAct(act);
				}
			}
			workFullMeetingminutesService.save(t,workFullManageId,submit);//保存
			if("reapply".equals(submit)){
				addMessage(redirectAttributes,"重新申请会议纪要，并发往部门负责人审核");
			} else if("repeal".equals(submit)){
				addMessage(redirectAttributes,"已撤销该会议纪要");
			}
			return "redirect:"+Global.getAdminPath()+"/workfullmeetingminutes/workFullMeetingminutes/?repage";
		}else{//新增表单保存
			workFullMeetingminutes = workFullMeetingminutesService.save(workFullMeetingminutes,workFullManageId,submit);//保存
			if("submit".equals(submit)){
				String message = StringUtils.isNoneBlank(workFullMeetingminutes.getId())?"保存会议纪要成功,并发往部门负责人审核":"会议纪要添加失败";
				addMessage(redirectAttributes,message);
			}else if("toStore".equals(submit)){
				String message = StringUtils.isNoneBlank(workFullMeetingminutes.getId())?"暂存会议纪要成功":"会议纪要暂存失败";
				addMessage(redirectAttributes,message);
			}
			//主页面添加操作后刷新主页面，弹窗页面添加操作后刷新弹窗页面
			if(StringUtils.isNotBlank(listpage)&&listpage.equals("workfullmanageList")){
				return "redirect:"+Global.getAdminPath()+"/workfullmeetingminutes/workFullMeetingminutes/"+listpage;
			}
			return "redirect:"+Global.getAdminPath()+"/workfullmeetingminutes/workFullMeetingminutes/?repage";
		}
	}
	/**
	 * 流程追踪
	 */
	@RequiresPermissions("workfullmeetingminutes:workFullMeetingminutes:view")
	@RequestMapping("getProcess")
	public String getProcess(WorkFullMeetingminutes workFullMeetingminutes, Model model){

		model.addAttribute("processInstanceId",workFullMeetingminutes.getProcessInstanceId());
		return "modules/workfullmeetingminutes/workFullMeetingminutesTask";
	}
	/**
	 * 待办任务
	 */
	@RequestMapping("auditTodo")
	public String auditTodo(Act act , Model model , HttpServletRequest request, HttpServletResponse response){
		act.setProcDefKey("workFullMeetingminutes");
		List<Act> actList = new ArrayList<>();
		actList.addAll(actTaskService.todoList(act));
		Office office = UserUtils.getSelectCompany();
		String companyId = office==null?"":office.getId();

		List<Activity> activities = activityService.groupByActivityMenu("a2d1b3bbff70432890acf20a18b05838",companyId);
		for (Activity activity:activities){
			act.setProcDefKey(activity.getProcessKey());
			actList.addAll(actTaskService.todoList(act));
		}

		List<WorkFullMeetingminutes> meetingList = new ArrayList<>();
		Role role = UserUtils.getSelectRole().get(0);
		String officeId = "";
		if("4".equals(role.getDataScope())){
			officeId = UserUtils.getUser().getOffice().getId();
		}

		for(Act a : actList){
			//重新申请和撤销不在代办和历史任务列表展示
			if("audit".equals(a.getTask().getTaskDefinitionKey())||(! "reapply".equals(a.getTask().getTaskDefinitionKey()) && !a.getTask().getTaskDefinitionKey().contains("audit"))){
				WorkFullMeetingminutes workFullMeetingminutes = workFullMeetingminutesService.getByProcessInstanceId(a.getProcInsId());
				if(workFullMeetingminutes != null){
					workFullMeetingminutes = workFullMeetingminutesService.get(workFullMeetingminutes.getId());
				}
				if(workFullMeetingminutes != null && workFullMeetingminutes.getCompanyId().equals(companyId)){
					User createBy = UserUtils.get(workFullMeetingminutes.getCreateBy().getId());
					if (StringUtils.isNotBlank(officeId)) {
						if (officeId.equals(createBy.getOffice().getId())) {
							if(a.getVars().getMap().get("applyUserId") != null){
								User user = UserUtils.get(a.getVars().getMap().get("applyUserId").toString());
								if(user != null){
									a.getVars().getMap().put("applyUserId",UserUtils.get(a.getVars().getMap().get("applyUserId").toString()).getName());
								}
							}
							workFullMeetingminutes.setAct(a);
							if(workFullMeetingminutes.getWorkFullManage()!=null && workFullMeetingminutes.getWorkFullManage().getId()!=null){
								WorkFullManage workFullManage = workFullManageService.get(workFullMeetingminutes.getWorkFullManage().getId());
								workFullMeetingminutes.setWorkFullManage(workFullManage);
							}
							if(StringUtils.isNotBlank(workFullMeetingminutes.getId())){
								workFullMeetingminutes.setName(officeService.get(companyId).getName());
							}
							meetingList.add(workFullMeetingminutes);
						}
					}else {
						if(a.getVars().getMap().get("applyUserId") != null){
							User user = UserUtils.get(a.getVars().getMap().get("applyUserId").toString());
							if(user != null){
								a.getVars().getMap().put("applyUserId",UserUtils.get(a.getVars().getMap().get("applyUserId").toString()).getName());
							}
						}
						workFullMeetingminutes.setAct(a);
						if(workFullMeetingminutes.getWorkFullManage()!=null && workFullMeetingminutes.getWorkFullManage().getId()!=null){
							WorkFullManage workFullManage = workFullManageService.get(workFullMeetingminutes.getWorkFullManage().getId());
							workFullMeetingminutes.setWorkFullManage(workFullManage);
						}
						if(StringUtils.isNotBlank(workFullMeetingminutes.getId())){
							workFullMeetingminutes.setName(officeService.get(companyId).getName());
						}
						meetingList.add(workFullMeetingminutes);
					}
				}
			}
		}

		model.addAttribute("list", meetingList);
		return "modules/workfullmeetingminutes/workFullMeetingminutesAuditTodo";

	}

	/**
	 *  打开审核框
	 */
	@RequestMapping("applyOnWorkFullMeetingminutes")
	public String applyOnWorkFullMeetingminutes(Act act){
		// 获取流程XML上的表单KEY
		String formKey = "/workfullmeetingminutes/workFullMeetingminutes/form";
		//logger.info("------formKeys:"+formKeys);
		// 获取流程实例对象
		if (act.getProcInsId() != null){
			if(actTaskService.getProcIns(act.getProcInsId())!=null){
				act.setProcIns(actTaskService.getProcIns(act.getProcInsId()));
			}else{
				act.setFinishedProcIns(actTaskService.getFinishedProcIns(act.getProcInsId()));
			}
		}
		return "redirect:" + ActUtils.getFormUrl(formKey, act);
	}
	/**
	 * 部门负责人审核
	 */
	@RequestMapping("saveAudit")
	public String saveAudit(WorkFullMeetingminutes workFullMeetingminutes, Map<String, Object> vars, Model model, RedirectAttributes redirectAttributes) {
		/*if (StringUtils.isBlank(workFullMeetingminutes.getAct().getComment())){
			addMessage(model, "请填写审核意见。");
			return form(workFullMeetingminutes, model,null);
		}*/
		String message = workFullMeetingminutesService.auditSave(workFullMeetingminutes);
		addMessage(redirectAttributes, message);
		return "redirect:"+Global.getAdminPath()+"/workfullmeetingminutes/workFullMeetingminutes/?repage";
	}
	/**
	 *  已办任务
	 */
	@RequestMapping("auditHistory")
	public String auditHistory(Act act , Model model,HttpServletRequest request,HttpServletResponse response){
		act.setProcDefKey("workFullMeetingminutes");
		List<Act> list = actTaskService.historicList(act);
		Office office = UserUtils.getSelectCompany();
		String companyId = office==null?"":office.getId();

		List<Activity> activities = activityService.groupByActivityMenu("a2d1b3bbff70432890acf20a18b05838",companyId);
		for (Activity activity:activities){
			act.setProcDefKey(activity.getProcessKey());
			list.addAll(actTaskService.historicList(act));
		}

		List<WorkFullMeetingminutes> meetingList = new ArrayList<WorkFullMeetingminutes>();
		Role role = UserUtils.getSelectRole().get(0);
		String officeId = "";
		if("4".equals(role.getDataScope())){
			officeId = UserUtils.getUser().getOffice().getId();
		}

		for (Act a : list) {
			//重新申请和撤销不展示在代办和历史任务列表里
			if(! "reapply".equals(a.getHistTask().getTaskDefinitionKey())){
				WorkFullMeetingminutes workFullMeetingminutes = workFullMeetingminutesService.getByProcessInstanceId(a.getHistTask().getProcessInstanceId());
				if(workFullMeetingminutes != null){
					workFullMeetingminutes = workFullMeetingminutesService.get(workFullMeetingminutes.getId());
				}
				if (workFullMeetingminutes != null && workFullMeetingminutes.getCompanyId().equals(companyId)) {
					User createBy = UserUtils.get(workFullMeetingminutes.getCreateBy().getId());
					if (StringUtils.isNotBlank(officeId)) {
						if (officeId.equals(createBy.getOffice().getId())) {
							if (a.getVars().getMap().get("applyUserId")!=null){
								a.getVars().getMap().put("applyUserId",UserUtils.get(a.getVars().getMap().get("applyUserId").toString()).getName());
							}
							workFullMeetingminutes.setAct(a);
							if(workFullMeetingminutes.getWorkFullManage()!=null && workFullMeetingminutes.getWorkFullManage().getId()!=null){
								WorkFullManage workFullManage = workFullManageService.get(workFullMeetingminutes.getWorkFullManage().getId());
								workFullMeetingminutes.setWorkFullManage(workFullManage);
							}
							if (StringUtils.isNotBlank(workFullMeetingminutes.getId())){
								workFullMeetingminutes.setName(officeService.get(companyId).getName());
							}
							meetingList.add(workFullMeetingminutes);
						}
					}else {
						if (a.getVars().getMap().get("applyUserId")!=null){
							a.getVars().getMap().put("applyUserId",UserUtils.get(a.getVars().getMap().get("applyUserId").toString()).getName());
						}
						workFullMeetingminutes.setAct(a);
						if(workFullMeetingminutes.getWorkFullManage()!=null && workFullMeetingminutes.getWorkFullManage().getId()!=null){
							WorkFullManage workFullManage = workFullManageService.get(workFullMeetingminutes.getWorkFullManage().getId());
							workFullMeetingminutes.setWorkFullManage(workFullManage);
						}
						if (StringUtils.isNotBlank(workFullMeetingminutes.getId())){
							workFullMeetingminutes.setName(officeService.get(companyId).getName());
						}
						meetingList.add(workFullMeetingminutes);
					}
				}
			}
		}

		model.addAttribute("list", meetingList);
		return "modules/workfullmeetingminutes/workFullMeetingminutesAuditHistory";
	}

	/**
	 * 删除会议纪要
	 */
	@RequiresPermissions("workfullmeetingminutes:workFullMeetingminutes:del")
	@RequestMapping(value = "delete")
	public String delete(WorkFullMeetingminutes workFullMeetingminutes,HttpServletRequest request,HttpServletResponse response, Model model) {
		workFullMeetingminutesService.delete(workFullMeetingminutes);
		WorkFullMeetingminutes w = new WorkFullMeetingminutes();
		w.setWorkFullManageId(workFullMeetingminutes.getWorkFullManageId());
		model.addAttribute("workFullMeetingminutes",w);
		model.addAttribute("message","删除会议纪要成功");
		return list(w,request,response,model);
	}
	
	/**
	 * 批量删除会议纪要
	 */
	@RequiresPermissions("workfullmeetingminutes:workFullMeetingminutes:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			workFullMeetingminutesService.delete(workFullMeetingminutesService.get(id));
		}
		addMessage(redirectAttributes, "删除会议纪要成功");
		return "redirect:"+Global.getAdminPath()+"/workfullmeetingminutes/workFullMeetingminutes/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("workfullmeetingminutes:workFullMeetingminutes:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(WorkFullMeetingminutes workFullMeetingminutes, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "会议纪要"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WorkFullMeetingminutes> page = workFullMeetingminutesService.findPage(new Page<WorkFullMeetingminutes>(request, response, -1), workFullMeetingminutes);
    		new ExportExcel("会议纪要", WorkFullMeetingminutes.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出会议纪要记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workfullmeetingminutes/workFullMeetingminutes/?repage";
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("workfullmeetingminutes:workFullMeetingminutes:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<WorkFullMeetingminutes> list = ei.getDataList(WorkFullMeetingminutes.class);
			for (WorkFullMeetingminutes workFullMeetingminutes : list){
				try{
					workFullMeetingminutesService.save(workFullMeetingminutes);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条会议纪要记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条会议纪要记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入会议纪要失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workfullmeetingminutes/workFullMeetingminutes/?repage";
    }
	
	/**
	 * 下载导入会议纪要数据模板
	 */
	@RequiresPermissions("workfullmeetingminutes:workFullMeetingminutes:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "会议纪要数据导入模板.xlsx";
    		List<WorkFullMeetingminutes> list = Lists.newArrayList(); 
    		new ExportExcel("会议纪要数据", WorkFullMeetingminutes.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workfullmeetingminutes/workFullMeetingminutes/?repage";
    }
	
	
	

}