/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.workadministrativeatamp.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.Office;
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.workadministrativeatamp.entity.WorkAdministrativeAtamp;
import com.jeeplus.modules.workadministrativeatamp.service.WorkAdministrativeAtampService;

/**
 * 行政盖章Controller
 * @author ssrh
 * @version 2018-07-10
 */
@Controller
@RequestMapping(value = "${adminPath}/workadministrativeatamp/workAdministrativeAtamp")
public class WorkAdministrativeAtampController extends BaseController {

	@Autowired
	private WorkAdministrativeAtampService workAdministrativeAtampService;
    @Autowired
    private ActTaskService actTaskService;
	
	@ModelAttribute
	public WorkAdministrativeAtamp get(@RequestParam(required=false) String id) {
		WorkAdministrativeAtamp entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workAdministrativeAtampService.get(id);
		}
		if (entity == null){
			entity = new WorkAdministrativeAtamp();
		}
		return entity;
	}
	
	/**
	 * 行政盖章列表页面
	 */
	@RequiresPermissions("workadministrativeatamp:workAdministrativeAtamp:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkAdministrativeAtamp workAdministrativeAtamp, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkAdministrativeAtamp> page = workAdministrativeAtampService.findPage(new Page<WorkAdministrativeAtamp>(request, response), workAdministrativeAtamp); 
		model.addAttribute("page", page);
		return "modules/workadministrativeatamp/workAdministrativeAtampList";
	}

	/**
	 * 查看，增加，编辑行政盖章表单页面
	 */
	@RequiresPermissions(value={"workadministrativeatamp:workAdministrativeAtamp:view","workadministrativeatamp:workAdministrativeAtamp:add","workadministrativeatamp:workAdministrativeAtamp:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkAdministrativeAtamp workAdministrativeAtamp, Model model) {
	    if(workAdministrativeAtamp.getComSign()==null||StringUtils.isBlank(workAdministrativeAtamp.getComSign().getId())){
            Office office = UserUtils.getSelectOffice();
            workAdministrativeAtamp.setOffice(office);
            if(StringUtils.isNotBlank(office.getBranchOffice())) {
                workAdministrativeAtamp.setComSign(UserUtils.getBranchOfficeById(office.getBranchOffice()));
            }else {
                workAdministrativeAtamp.setComSign(UserUtils.getSelectCompany());
            }
        }
        if(workAdministrativeAtamp.getSubmitDate()==null){
	        workAdministrativeAtamp.setSubmitDate(new Date());
        }
        if(workAdministrativeAtamp.getSubmiter()==null){
	        workAdministrativeAtamp.setSubmiter(UserUtils.getUser());
        }
        if(workAdministrativeAtamp.getOffice()==null||StringUtils.isBlank(workAdministrativeAtamp.getOffice().getId())){
	        workAdministrativeAtamp.setOffice(UserUtils.getSelectOffice());
        }
		model.addAttribute("workAdministrativeAtamp", workAdministrativeAtamp);
		return "modules/workadministrativeatamp/workAdministrativeAtampForm";
	}

	/**
	 * 查看，增加，编辑行政盖章表单页面
	 */
	@RequiresPermissions(value={"workadministrativeatamp:workAdministrativeAtamp:view"},logical=Logical.OR)
	@RequestMapping(value = "view")
	public String view(WorkAdministrativeAtamp workAdministrativeAtamp, Model model) {
		model.addAttribute("workAdministrativeAtamp", workAdministrativeAtamp);
		return "modules/workadministrativeatamp/workAdministrativeAtampView";
	}

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

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

	/**
	 * 导入Excel数据

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

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

        model.addAttribute("workAdministrativeAtamp", workAdministrativeAtamp);
        return "modules/workadministrativeatamp/workAdministrativeAtampModifyApply";
    }

    /**
     * 工单执行（完成任务）
     * @param model
     * @return
     */
    @RequestMapping(value = "saveAudit")
    public String saveAudit(WorkAdministrativeAtamp workAdministrativeAtamp, Model model,
                            RedirectAttributes redirectAttributes) {
        try {
            // 对不同环节的业务逻辑进行操作
            String taskDefKey = workAdministrativeAtamp.getAct().getTaskDefKey();
            List<User> users = null;
            if ("bmzr".equals(taskDefKey)){
                users = UserUtils.getByProssType(workAdministrativeAtamp.getProcessInstanceId(),2);
                if (users==null )
                    users = UserUtils.getByRoleActivityEnname("fgld",2,UserUtils.getSelectOffice().getId(),"11",workAdministrativeAtamp.getCreateBy());
            }else  if ("fgld".equals(taskDefKey)){
                users = UserUtils.getByProssType(workAdministrativeAtamp.getProcessInstanceId(),3);
                if (users==null )
                    users = UserUtils.getByRoleActivityEnname("gzr",3,workAdministrativeAtamp.getComSign().getId(),"11",workAdministrativeAtamp.getCreateBy());
            }else if ("gzr".equals(taskDefKey)){
                users = UserUtils.getByProssType(workAdministrativeAtamp.getProcessInstanceId(),3);
            }else if ("modifyApply".equals(taskDefKey)){
                users = UserUtils.getByProssType(workAdministrativeAtamp.getProcessInstanceId(),1);
            }
            String flag = workAdministrativeAtamp.getAct().getFlag();
            if ("yes".equals(flag) && (users==null || users.size()==0)){
                addMessage(redirectAttributes, "审批失败,审批人为空,请联系管理员！");
            }else {
                String str = workAdministrativeAtampService.auditSave(workAdministrativeAtamp,users);
                addMessage(redirectAttributes, str);
            }
        }catch (Exception e){
            logger.info("Exception e:"+e);
            addMessage(redirectAttributes, "审批失败");
        }
        if (StringUtils.isNotBlank(workAdministrativeAtamp.getHome()) && "home".equals(workAdministrativeAtamp.getHome())){
            return "redirect:" + Global.getAdminPath() + "/home/?repage";
        }else {
            return "redirect:" + Global.getAdminPath() + "/workadministrativeatamp/workAdministrativeAtamp/?repage";
        }
    }

    //	审批页面
    @RequestMapping(value = "audit")
    public String workContractInfoAudit(Act act, WorkAdministrativeAtamp workAdministrativeAtamp, 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())) {
            workAdministrativeAtamp.setAct(act);
            model.addAttribute("processInstanceId", workAdministrativeAtamp.getProcessInstanceId());
        }
        model.addAttribute("workAdministrativeAtamp", workAdministrativeAtamp);
        return "modules/workadministrativeatamp/workAdministrativeAtampAudit";
    }

    @RequestMapping(value = "getProcess")
    public String getProcess(WorkAdministrativeAtamp workAdministrativeAtamp, Model model, HttpServletRequest request){
        model.addAttribute("processInstanceId", workAdministrativeAtamp.getProcessInstanceId());
        return "modules/workadministrativeatamp/workAdministrativeAtampTask";
    }

    @RequiresPermissions(value={"workadministrativeatamp:workAdministrativeAtamp: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 {
            WorkAdministrativeAtamp workAdministrativeAtamp = workAdministrativeAtampService.get(id);
            if(5==workAdministrativeAtamp.getState()){
                addMessage(redirectAttributes, "行政盖章已审批通过，无法撤回");
                return "redirect:"+Global.getAdminPath()+"/workadministrativeatamp/workAdministrativeAtamp/?repage";
            }
            workAdministrativeAtampService.cancelProcess(workAdministrativeAtamp);
            addMessage(redirectAttributes, "撤回该盖章审批成功");
        }catch (Exception e){
            logger.info(e.getMessage());
            addMessage(redirectAttributes, "撤回该盖章审批失败");
        }
        return "redirect:" + Global.getAdminPath() + "/workadministrativeatamp/workAdministrativeAtamp/?repage";
    }
}