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

import java.util.ArrayList;
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.workdailyroutine.entity.WorkDailyRoutine;
import com.jeeplus.modules.workdailyroutine.entity.WorkDailyRoutineDetail;
import com.jeeplus.modules.workdailyroutine.service.WorkDailyRoutineDetailService;
import com.jeeplus.modules.workreceiptssettle.entity.WorkReceiptsSettle;
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.workincomingmessage.entity.WorkIncomingMessage;
import com.jeeplus.modules.workincomingmessage.service.WorkIncomingMessageService;

/**
 * 收文管理Controller
 * @author ssrh
 * @version 2018-07-10
 */
@Controller
@RequestMapping(value = "${adminPath}/workincomingmessage/workIncomingMessage")
public class WorkIncomingMessageController extends BaseController {

	@Autowired
	private WorkIncomingMessageService workIncomingMessageService;
    @Autowired
    private ActTaskService actTaskService;
    @Autowired
    private WorkDailyRoutineDetailService routineDetailService;
	
	@ModelAttribute
	public WorkIncomingMessage get(@RequestParam(required=false) String id) {
		WorkIncomingMessage entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workIncomingMessageService.get(id);
		}
		if (entity == null){
			entity = new WorkIncomingMessage();
		}
		return entity;
	}
	
	/**
	 * 收文管理列表页面
	 */
	@RequiresPermissions("workincomingmessage:workIncomingMessage:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkIncomingMessage workIncomingMessage, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkIncomingMessage> page = workIncomingMessageService.findPage(new Page<WorkIncomingMessage>(request, response), workIncomingMessage); 
		model.addAttribute("page", page);
		return "modules/workincomingmessage/workIncomingMessageList";
	}

	/**
	 * 查看，增加，编辑收文管理表单页面
	 */
	@RequiresPermissions(value={"workincomingmessage:workIncomingMessage:add","workincomingmessage:workIncomingMessage:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkIncomingMessage workIncomingMessage, Model model) {
	    if(workIncomingMessage.getCreateBy()==null||StringUtils.isBlank(workIncomingMessage.getCreateBy().getId())){
	        workIncomingMessage.setCreateBy(UserUtils.getUser());
        }
        if(workIncomingMessage.getOffice()==null || StringUtils.isBlank(workIncomingMessage.getOffice().getId())){
	        workIncomingMessage.setOffice(UserUtils.getSelectOffice());
        }
        if(StringUtils.isBlank(workIncomingMessage.getCounts())){
	        workIncomingMessage.setCounts("1");
        }
		model.addAttribute("workIncomingMessage", workIncomingMessage);
		return "modules/workincomingmessage/workIncomingMessageForm";
	}

	/**
	 * 查看，增加，编辑收文管理表单页面
	 */
	@RequiresPermissions(value={"workincomingmessage:workIncomingMessage:view"},logical=Logical.OR)
	@RequestMapping(value = "view")
	public String view(WorkIncomingMessage workIncomingMessage, Model model) {
	    if(StringUtils.isNotBlank(workIncomingMessage.getDailyId())&&!"NoN".equals(workIncomingMessage.getDailyId())){
            WorkDailyRoutineDetail routineDetail = new WorkDailyRoutineDetail();
            routineDetail.setWorkDailyRoutine(new WorkDailyRoutine(workIncomingMessage.getDailyId()));
            workIncomingMessage.setDetailList(routineDetailService.findList(routineDetail));
        }
		model.addAttribute("workIncomingMessage", workIncomingMessage);
		return "modules/workincomingmessage/workIncomingMessageView";
	}

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

	/**
	 * 导入Excel数据

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

    @RequiresPermissions(value={"workincomingmessage:workIncomingMessage:edit"},logical=Logical.OR)
    @RequestMapping(value = "modify")
    public String modify(WorkIncomingMessage workIncomingMessage, Model model,RedirectAttributes redirectAttributes) {
        workIncomingMessage=workIncomingMessageService.get(workIncomingMessage.getId());
        ProcessInstance processInstance = actTaskService.getProcIns(workIncomingMessage.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);
            workIncomingMessage.setAct(act);
        }

        model.addAttribute("workIncomingMessage", workIncomingMessage);
        return "modules/workincomingmessage/workIncomingMessageModifyApply";
    }

    /**
     * 工单执行（完成任务）
     * @param model
     * @return
     */
    @RequestMapping(value = "saveAudit")
    public String saveAudit(WorkIncomingMessage workIncomingMessage, Model model,
                            RedirectAttributes redirectAttributes) {
        // 对不同环节的业务逻辑进行操作
        String taskDefKey = workIncomingMessage.getAct().getTaskDefKey();
        List<User> users = null;
        if ("xzzg".equals(taskDefKey)){
            users = UserUtils.getByProssType(workIncomingMessage.getProcessInstanceId(),2);
            if (users==null )
                users = UserUtils.getByRoleActivityEnname("zjl",3,workIncomingMessage.getOffice().getId(),"11",workIncomingMessage.getCreateBy());
        }else if ("zjl".equals(taskDefKey)){
            users = new ArrayList<>();
            users.add(workIncomingMessage.getCreateBy());
        }else if ("consume".equals(taskDefKey)){
            users = new ArrayList<>();
            users.add(workIncomingMessage.getCreateBy());
        }else if ("modifyApply".equals(taskDefKey)){
            users = UserUtils.getByProssType(workIncomingMessage.getProcessInstanceId(),1);
        }
        String flag = workIncomingMessage.getAct().getFlag();
        if ("yes".equals(flag) && (users==null || users.size()==0)){
            addMessage(redirectAttributes, "审批失败,审批人为空,请联系管理员！");
        }else {
            String str = workIncomingMessageService.auditSave(workIncomingMessage, users);
            addMessage(redirectAttributes, str);
        }
        if (StringUtils.isNotBlank(workIncomingMessage.getHome()) && "home".equals(workIncomingMessage.getHome())){
            return "redirect:" + Global.getAdminPath() + "/home/?repage";
        }else {
            return "redirect:" + Global.getAdminPath() + "/workincomingmessage/workIncomingMessage/?repage";
        }
    }

    //	审批页面
    @RequestMapping(value = "audit")
    public String workContractInfoAudit(Act act, WorkIncomingMessage workIncomingMessage, Model model) {

        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())) {
            workIncomingMessage.setAct(act);
            model.addAttribute("processInstanceId", workIncomingMessage.getProcessInstanceId());
        }
        model.addAttribute("workIncomingMessage", workIncomingMessage);
        return "modules/workincomingmessage/workIncomingMessageAudit";
    }

    @RequestMapping(value = "getProcess")
    public String getProcess(WorkIncomingMessage workIncomingMessage, Model model, HttpServletRequest request){
        model.addAttribute("processInstanceId", workIncomingMessage.getProcessInstanceId());
        return "modules/workincomingmessage/workIncomingMessageTask";
    }

    @RequiresPermissions(value={"workincomingmessage:workIncomingMessage: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 {
            WorkIncomingMessage workIncomingMessage = workIncomingMessageService.get(id);
            if(5==workIncomingMessage.getState()){
                addMessage(redirectAttributes, "收文管理已审批通过，无法撤回");
                return "redirect:"+Global.getAdminPath()+"/workincomingmessage/workIncomingMessage/?repage";
            }
            workIncomingMessageService.cancelProcess(workIncomingMessage);
            addMessage(redirectAttributes, "撤回该收文审批成功");
        }catch (Exception e){
            logger.info(e.getMessage());
            addMessage(redirectAttributes, "撤回该收文审批失败");
        }
        return "redirect:" + Global.getAdminPath() + "/workincomingmessage/workIncomingMessage/?repage";
    }

    @RequiresPermissions(value={"workincomingmessage:workIncomingMessage:add","workincomingmessage:workIncomingMessage:edit"},logical=Logical.OR)
    @RequestMapping(value = "tstore")
    public String tStore(WorkIncomingMessage workIncomingMessage, Model model, RedirectAttributes redirectAttributes) throws Exception{
        if (!beanValidator(model, workIncomingMessage)){
            return form(workIncomingMessage, model);
        }
        try {
            workIncomingMessage.setState(ProjectStatusEnum.TSTORE.getValue());
            if (!workIncomingMessage.getIsNewRecord()) {//编辑表单保存
                WorkIncomingMessage t = workIncomingMessageService.get(workIncomingMessage.getId());//从数据库取出记录的值
                MyBeanUtils.copyBeanNotNull2Bean(workIncomingMessage, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
                workIncomingMessageService.save(t);//保存
            } else {//新增表单保存
                workIncomingMessageService.save(workIncomingMessage);//保存
            }
            addMessage(redirectAttributes, "暂存收文管理成功");
        }catch (Exception e){
            logger.error("暂存收文管理异常：",e);
            addMessage(redirectAttributes, "暂存收文管理异常:"+e.getMessage());
        }
        return "redirect:"+Global.getAdminPath()+"/workincomingmessage/workIncomingMessage/?repage";
    }
}