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

import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.modules.act.entity.Act;
import com.jeeplus.modules.act.service.ActTaskService;
import com.jeeplus.modules.projectrecord.enums.ProjectStatusEnum;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workincomingmessage.entity.WorkIncomingMessage;
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 com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.MyBeanUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.worksendmessage.entity.WorkSendMessage;
import com.jeeplus.modules.worksendmessage.service.WorkSendMessageService;

/**
 * 发文管理Controller
 * @author ssrh
 * @version 2018-07-12
 */
@Controller
@RequestMapping(value = "${adminPath}/worksendmessage/workSendMessage")
public class WorkSendMessageController extends BaseController {

	@Autowired
	private WorkSendMessageService workSendMessageService;
    @Autowired
    private ActTaskService actTaskService;
	
	@ModelAttribute
	public WorkSendMessage get(@RequestParam(required=false) String id) {
		WorkSendMessage entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workSendMessageService.get(id);
		}
		if (entity == null){
			entity = new WorkSendMessage();
		}
		return entity;
	}
	
	/**
	 * 发文管理列表页面
	 */
	@RequiresPermissions("worksendmessage:workSendMessage:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkSendMessage workSendMessage, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkSendMessage> page = workSendMessageService.findPage(new Page<WorkSendMessage>(request, response), workSendMessage); 
		model.addAttribute("page", page);
		return "modules/worksendmessage/workSendMessageList";
	}

	/**
	 * 查看，增加，编辑发文管理表单页面
	 */
	@RequiresPermissions(value={"worksendmessage:workSendMessage:add","worksendmessage:workSendMessage:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkSendMessage workSendMessage, Model model) {
	    if(workSendMessage.getCreateDate()==null){
	        workSendMessage.setCreateDate(new Date());
        }
        if(StringUtils.isNotBlank(workSendMessage.getId())){
            workSendMessageService.queryDetails(workSendMessage);
        }
        if(workSendMessage.getOffice()==null||StringUtils.isBlank(workSendMessage.getOffice().getId())){
	        workSendMessage.setOffice(UserUtils.getSelectOffice());
        }
		model.addAttribute("workSendMessage", workSendMessage);
		return "modules/worksendmessage/workSendMessageForm";
	}

    /**
     * 查看，增加，编辑收文管理表单页面
     */
    @RequiresPermissions(value={"worksendmessage:workSendMessage:view"},logical=Logical.OR)
    @RequestMapping(value = "view")
    public String view(WorkSendMessage workSendMessage, Model model) {
        if(StringUtils.isNotBlank(workSendMessage.getId())){
            workSendMessageService.queryDetails(workSendMessage);
        }
        model.addAttribute("workSendMessage", workSendMessage);
        return "modules/worksendmessage/workSendMessageView";
    }

    /**
     * 发文管理列表页面
     */
    @RequestMapping(value = {"memberList"})
    public String memberList(WorkSendMessage workSendMessage, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<WorkSendMessage> page = workSendMessageService.findMemberPage(new Page<WorkSendMessage>(request, response), workSendMessage);
        model.addAttribute("page", page);
        return "modules/worksendmessage/workSendMessageMemberList";
    }

    /**
     * 查看，增加，编辑收文管理表单页面
     */
    @RequestMapping(value = "memberView")
    public String memberView(WorkSendMessage workSendMessage, Model model) {
        if(StringUtils.isNotBlank(workSendMessage.getId())){
            workSendMessageService.queryDetails(workSendMessage);
        }
        model.addAttribute("workSendMessage", workSendMessage);
        return "modules/worksendmessage/workSendMessageMemberView";
    }

	/**
	 * 保存发文管理
	 */
	@RequiresPermissions(value={"worksendmessage:workSendMessage:add","worksendmessage:workSendMessage:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(WorkSendMessage workSendMessage, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workSendMessage)){
			return form(workSendMessage, model);
		}
        workSendMessage.setState(ProjectStatusEnum.IN_APRL.getValue());
        String str = "";
        if(!workSendMessage.getIsNewRecord()){//编辑表单保存
            WorkSendMessage t = workSendMessageService.get(workSendMessage.getId());//从数据库取出记录的值
            MyBeanUtils.copyBeanNotNull2Bean(workSendMessage, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
            str = workSendMessageService.saveMessage(t);//保存
        }else{//新增表单保存
            str = workSendMessageService.saveMessage(workSendMessage);//保存
        }
        if (StringUtils.isNotBlank(str)){
            addMessage(redirectAttributes, "保存发文管理失败:"+str);
        }else {
            addMessage(redirectAttributes, "保存发文管理成功");
        }
		return "redirect:"+Global.getAdminPath()+"/worksendmessage/workSendMessage/?repage";
	}
	/**
	 * 保存发文管理
	 */
	@RequiresPermissions(value={"worksendmessage:workSendMessage:add","worksendmessage:workSendMessage:edit"},logical=Logical.OR)
	@RequestMapping(value = "tstore")
	public String tstore(WorkSendMessage workSendMessage, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workSendMessage)){
			return form(workSendMessage, model);
		}
        workSendMessage.setState(ProjectStatusEnum.TSTORE.getValue());
        if(!workSendMessage.getIsNewRecord()){//编辑表单保存
            WorkSendMessage t = workSendMessageService.get(workSendMessage.getId());//从数据库取出记录的值
            MyBeanUtils.copyBeanNotNull2Bean(workSendMessage, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
            workSendMessageService.save(t);//保存
        }else{//新增表单保存
            workSendMessageService.save(workSendMessage);//保存
        }
        addMessage(redirectAttributes, "暂存发文管理成功");
		return "redirect:"+Global.getAdminPath()+"/worksendmessage/workSendMessage/?repage";
	}
	
	/**
	 * 删除发文管理
	 */
	@RequiresPermissions("worksendmessage:workSendMessage:del")
	@RequestMapping(value = "delete")
	public String delete(WorkSendMessage workSendMessage, RedirectAttributes redirectAttributes) {
        Integer sta = workSendMessage.getState();
        if(5==sta|| 2==sta){
            if(5==sta){
                addMessage(redirectAttributes, "发文信息已审批通过，无法删除");
                return "redirect:"+Global.getAdminPath()+"/worksendmessage/workSendMessage/?repage";
            }else{
                addMessage(redirectAttributes, "发文信息正在审核中，无法删除");
                return "redirect:"+Global.getAdminPath()+"/worksendmessage/workSendMessage/?repage";
            }
        }
		workSendMessageService.delete(workSendMessage);
		addMessage(redirectAttributes, "删除发文管理成功");
		return "redirect:"+Global.getAdminPath()+"/worksendmessage/workSendMessage/?repage";
	}
	
	/**
	 * 批量删除发文管理
	 */
	@RequiresPermissions("worksendmessage:workSendMessage:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			workSendMessageService.delete(workSendMessageService.get(id));
		}
		addMessage(redirectAttributes, "删除发文管理成功");
		return "redirect:"+Global.getAdminPath()+"/worksendmessage/workSendMessage/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("worksendmessage:workSendMessage:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(WorkSendMessage workSendMessage, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "发文管理"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WorkSendMessage> page = workSendMessageService.findPage(new Page<WorkSendMessage>(request, response, -1), workSendMessage);
    		new ExportExcel("发文管理", WorkSendMessage.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出发文管理记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/worksendmessage/workSendMessage/?repage";
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("worksendmessage:workSendMessage: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<WorkSendMessage> list = ei.getDataList(WorkSendMessage.class);
			for (WorkSendMessage workSendMessage : list){
				try{
					workSendMessageService.save(workSendMessage);
					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()+"/worksendmessage/workSendMessage/?repage";
    }
	
	/**
	 * 下载导入发文管理数据模板
	 */
	@RequiresPermissions("worksendmessage:workSendMessage:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "发文管理数据导入模板.xlsx";
    		List<WorkSendMessage> list = Lists.newArrayList(); 
    		new ExportExcel("发文管理数据", WorkSendMessage.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/worksendmessage/workSendMessage/?repage";
    }

    @RequiresPermissions(value={"worksendmessage:workSendMessage:edit"},logical=Logical.OR)
    @RequestMapping(value = "modify")
    public String modify(WorkSendMessage workSendMessage, Model model,RedirectAttributes redirectAttributes) {
        workSendMessage=workSendMessageService.get(workSendMessage.getId());
        if(StringUtils.isNotBlank(workSendMessage.getId())){
            workSendMessageService.queryDetails(workSendMessage);
        }
        ProcessInstance processInstance = actTaskService.getProcIns(workSendMessage.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);
            workSendMessage.setAct(act);
        }

        model.addAttribute("workSendMessage", workSendMessage);
        return "modules/worksendmessage/workSendMessageModifyApply";
    }

    /**
     * 工单执行（完成任务）
     * @param model
     * @return
     */
    @RequestMapping(value = "saveAudit")
    public String saveAudit(WorkSendMessage workSendMessage, Model model,
                            RedirectAttributes redirectAttributes) {
        try {
            List<User> users = UserUtils.getByProssType(workSendMessage.getProcessInstanceId(),1);
            String flag = workSendMessage.getAct().getFlag();
            if ("yes".equals(flag) && (users==null || users.size()==0)){
                addMessage(redirectAttributes, "审批失败,审批人为空,请联系管理员！");
            }else {
                String str = workSendMessageService.auditSave(workSendMessage, users);
                addMessage(redirectAttributes, str);
            }
        }catch (Exception e){
            addMessage(redirectAttributes, "发文管理流程审批失败");
        }

        if (StringUtils.isNotBlank(workSendMessage.getHome()) && "home".equals(workSendMessage.getHome())){
            return "redirect:" + Global.getAdminPath() + "/home/?repage";
        }else {
            return "redirect:" + Global.getAdminPath() + "/worksendmessage/workSendMessage/?repage";
        }
    }

    //	审批页面
    @RequestMapping(value = "audit")
    public String workContractInfoAudit(Act act, WorkSendMessage workSendMessage, Model model) {
        if(StringUtils.isNotBlank(workSendMessage.getId())){
            workSendMessageService.queryDetails(workSendMessage);
        }
        if (act.getProcInsId() != null) {
            if (actTaskService.getProcIns(act.getProcInsId()) != null) {
                act.setProcIns(actTaskService.getProcIns(act.getProcInsId()));
            } else {
                act.setFinishedProcIns(actTaskService.getFinishedProcIns(act.getProcInsId()));
            }
        }
        if (act != null && StringUtils.isNotBlank(act.getTaskId())) {
            workSendMessage.setAct(act);
            model.addAttribute("processInstanceId", workSendMessage.getProcessInstanceId());
        }
        model.addAttribute("workSendMessage", workSendMessage);
        return "modules/worksendmessage/workSendMessageAudit";
    }

    @RequestMapping(value = "getProcess")
    public String getProcess(WorkSendMessage workSendMessage, Model model, HttpServletRequest request){
        model.addAttribute("processInstanceId", workSendMessage.getProcessInstanceId());
        return "modules/worksendmessage/workSendMessageTask";
    }

    @RequiresPermissions(value={"worksendmessage:workSendMessage:edit"},logical=Logical.OR)
    @RequestMapping(value = "revoke")
    public String revoke(HttpServletRequest request, RedirectAttributes redirectAttributes) {
        HashMap<String, String> requestMap = findRequestMap(request);
        String processInstanceId = requestMap.get("processInstanceId");
        String id = requestMap.get("id");
        try {
            WorkSendMessage workSendMessage = workSendMessageService.get(id);
            if(5==workSendMessage.getState()){
                addMessage(redirectAttributes, "发文信息已审批通过，无法撤回");
                return "redirect:"+Global.getAdminPath()+"/worksendmessage/workSendMessage/?repage";
            }
            workSendMessageService.cancelProcess(workSendMessage);
            addMessage(redirectAttributes, "撤回该发文审批成功");
        }catch (Exception e){
            logger.info(e.getMessage());
            addMessage(redirectAttributes, "撤回该发文审批失败");
        }
        return "redirect:" + Global.getAdminPath() + "/worksendmessage/workSendMessage/?repage";
    }
}