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

import com.google.common.collect.Lists;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
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.workfulldesignchange.entity.WorkFullDesignchange;
import com.jeeplus.modules.workfulldesignchange.service.WorkFullDesignchangeService;
import com.jeeplus.modules.workfullmanage.entity.WorkFullManage;
import com.jeeplus.modules.workfullmanage.service.WorkFullManageService;
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.*;
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-03
 */
@SuppressWarnings("all")
@Controller
@RequestMapping(value = "${adminPath}/workfulldesignchange/workFullDesignchange")
public class WorkFullDesignchangeController extends BaseController {

	@Autowired
	private WorkFullManageService workFullManageService;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private ActTaskService actTaskService;
	@Autowired
	private WorkFullDesignchangeService workFullDesignchangeService;
	@Autowired
	private ActivityService activityService;

	@ModelAttribute
	public WorkFullDesignchange get(@RequestParam(required=false) String id) {
		WorkFullDesignchange entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workFullDesignchangeService.get(id);
		}
		if (entity == null){
			entity = new WorkFullDesignchange();
		}
		return entity;
	}
	/**
	 *  待添加设计变更的项目列表
	 */
	@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 = workFullDesignchangeService.findListOfWorkFullManage(new Page<WorkFullManage>(request, response), workFullManage);
		model.addAttribute("page", page);
		return "modules/workfulldesignchange/workfullmanageList";
	}

	 /**
	 * 设计变更列表页面
	 */
	@RequiresPermissions("workfulldesignchange:workFullDesignchange:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkFullDesignchange workFullDesignchange, HttpServletRequest request, HttpServletResponse response, Model model) {
		String workFullManageId = request.getParameter("workFullManageId");

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

		return "modules/workfulldesignchange/workFullDesignchangeList";
	}

	/**
	 * 查看，增加，编辑设计变更表单页面
	 */
	@RequiresPermissions(value={"workfulldesignchange:workFullDesignchange:view","workfulldesignchange:workFullDesignchange:add","workfulldesignchange:workFullDesignchange:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkFullDesignchange workFullDesignchange, Model model,HttpServletRequest request) {
		String dialog = request.getParameter("dialog");
		String workFullManageId = request.getParameter("workFullManageId");
		String listpage = request.getParameter("listpage");
		if(StringUtils.isBlank(workFullManageId)){
			workFullManageId = workFullDesignchange.getWorkFullManageId();
		}
		if(StringUtils.isNotBlank(workFullManageId)){
			WorkFullManage workFullManage = workFullManageService.get(workFullManageId);
			model.addAttribute("workFullManage",workFullManage);
		}
		model.addAttribute("workFullDesignchange", workFullDesignchange);
		model.addAttribute("listpage",listpage);

		if(workFullDesignchange.getAct()!=null && StringUtils.isNotBlank(workFullDesignchange.getAct().getTaskId())){
			String taskId = workFullDesignchange.getAct().getTaskId();
			return "modules/workfulldesignchange/workFullDesignchangeAudit";
		}

		if("add".equals(dialog) || "edit".equals(dialog)){
			return "modules/workfulldesignchange/workFullDesignchangeForm";
		}
		if("view".equals(dialog)){
			return "modules/workfulldesignchange/workFullDesignchangeView";
		}
		return "modules/workfulldesignchange/workFullDesignchangeForm";
	}

	/**
	 * 保存设计变更
	 */
	@RequiresPermissions(value={"workfulldesignchange:workFullDesignchange:add","workfulldesignchange:workFullDesignchange:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(WorkFullDesignchange workFullDesignchange,HttpServletRequest request,@RequestParam(value = "listpage",required = false)String listpage,
					   Model model,RedirectAttributes redirectAttributes) throws Exception{
		//新添加（submit提交，toStore暂存），被驳回（reapply重新申请，repeal撤销）
		String submit = request.getParameter("submit");
		String workFullManageId = request.getParameter("workFullManageId");
		if (!beanValidator(model, workFullDesignchange)){
			return form(workFullDesignchange, model,request);
		}
		if(!workFullDesignchange.getIsNewRecord()){//编辑表单保存
			WorkFullDesignchange t = workFullDesignchangeService.get(workFullDesignchange.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workFullDesignchange, 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);
				}
			}
			workFullDesignchangeService.save(t,workFullManageId,submit);//保存
			if("reapply".equals(submit)){
				addMessage(redirectAttributes,"重新申请设计变更，并发往部门负责人审核");
			} else if("repeal".equals(submit)){
				addMessage(redirectAttributes,"已撤销设计变更");
			}
			return "redirect:"+Global.getAdminPath()+"/workfulldesignchange/workFullDesignchange/?repage";
		}else{//新增表单保存
			workFullDesignchange = workFullDesignchangeService.save(workFullDesignchange,workFullManageId,submit);//保存
			if("submit".equals(submit)){
				String message = StringUtils.isNoneBlank(workFullDesignchange.getId())?"保存设计变更成功,并发往部门负责人审核":"监理联系单添加失败";
				addMessage(redirectAttributes,message);
			}else if("toStore".equals(submit)){
				String message = StringUtils.isNoneBlank(workFullDesignchange.getId())?"已暂存设计变更":"暂存设计变更失败";
				addMessage(redirectAttributes,message);
			}
			//主页面添加操作后刷新主页面，弹窗页面添加操作后刷新弹窗页面
			if(StringUtils.isNotBlank(listpage)&&listpage.equals("workfullmanageList")){
				return "redirect:"+Global.getAdminPath()+"/workfulldesignchange/workFullDesignchange/"+listpage;
			}
			return "redirect:"+Global.getAdminPath()+"/workfulldesignchange/workFullDesignchange/?repage";
		}
	}
	/**
	 * 流程追踪
	 */
	@RequiresPermissions("workfulldesignchange:workFullDesignchange:view")
	@RequestMapping("getProcess")
	public String getProcess(WorkFullDesignchange workFullDesignchange, Model model){

		model.addAttribute("processInstanceId",workFullDesignchange.getProcessInstanceId());
		return "modules/workfulldesignchange/workFullDesignchangeTask";
	}
	/**
	 * 待办任务
	 */
	@RequestMapping("auditTodo")
	public String auditTodo(Act act , Model model , HttpServletRequest request, HttpServletResponse response){
		act.setProcDefKey("workFullDesignchange");
		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("c2660a7b49e14a70b411ed36535662d4",companyId);
		for (Activity activity:activities){
			act.setProcDefKey(activity.getProcessKey());
			actList.addAll(actTaskService.todoList(act));
		}

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

		for(Act a : actList){
			//重新申请和撤销不在代办和历史任务列表展示
			if("audit".equals(a.getTask().getTaskDefinitionKey())||(! "reapply".equals(a.getTask().getTaskDefinitionKey()) && !a.getTask().getTaskDefinitionKey().contains("audit"))){
				WorkFullDesignchange workFullDesignchange = workFullDesignchangeService.getByProcessInstanceId(a.getProcInsId());
				if(workFullDesignchange != null){
					workFullDesignchange = workFullDesignchangeService.get(workFullDesignchange.getId());
				}
				if(workFullDesignchange != null && workFullDesignchange.getCompanyId().equals(companyId)){
					User createBy = UserUtils.get(workFullDesignchange.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());
								}
							}
							workFullDesignchange.setAct(a);
							if(workFullDesignchange.getWorkFullManage()!=null && workFullDesignchange.getWorkFullManage().getId()!=null){
								WorkFullManage workFullManage = workFullManageService.get(workFullDesignchange.getWorkFullManage().getId());
								workFullDesignchange.setWorkFullManage(workFullManage);
							}
							if(StringUtils.isNotBlank(workFullDesignchange.getId())){
								workFullDesignchange.setName(officeService.get(companyId).getName());
							}
							designList.add(workFullDesignchange);
						}
					}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());
							}
						}
						workFullDesignchange.setAct(a);
						if(workFullDesignchange.getWorkFullManage()!=null && workFullDesignchange.getWorkFullManage().getId()!=null){
							WorkFullManage workFullManage = workFullManageService.get(workFullDesignchange.getWorkFullManage().getId());
							workFullDesignchange.setWorkFullManage(workFullManage);
						}
						if(StringUtils.isNotBlank(workFullDesignchange.getId())){
							workFullDesignchange.setName(officeService.get(companyId).getName());
						}
						designList.add(workFullDesignchange);
					}
				}
			}
		}

		model.addAttribute("list", designList);
		return "modules/workfulldesignchange/workFullDesignchangeAuditTodo";

	}
	/**
	 *  打开审核框
	 */
	@RequestMapping("applyOnWorkFullDesignchange")
	public String applyOnWorkFullDesignchange(Act act){
		// 获取流程XML上的表单KEY
		String formKey = "/workfulldesignchange/workFullDesignchange/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(WorkFullDesignchange workFullDesignchange, Map<String, Object> vars, Model model, RedirectAttributes redirectAttributes) {
		/*if (StringUtils.isBlank(workFullDesignchange.getAct().getComment())){
			addMessage(model, "请填写审核意见。");
			return form(workFullDesignchange, model,null);
		}*/
		String message = workFullDesignchangeService.auditSave(workFullDesignchange);
		addMessage(redirectAttributes, message);
		return "redirect:"+Global.getAdminPath()+"/workfulldesignchange/workFullDesignchange/?repage";
	}
	/**
	 *  已办任务
	 */
	@RequestMapping("auditHistory")
	public String auditHistory(Act act , Model model,HttpServletRequest request,HttpServletResponse response){
		act.setProcDefKey("workFullDesignchange");
		List<Act> list = actTaskService.historicList(act);
		Office office = UserUtils.getSelectCompany();
		String companyId = office==null?"":office.getId();

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

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

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

		model.addAttribute("list", meetingList);
		return "modules/workfulldesignchange/workFullDesignchangeAuditHistory";
	}
	/**
	 * 删除设计变更
	 */
	@RequiresPermissions("workfulldesignchange:workFullDesignchange:del")
	@RequestMapping(value = "delete")
	public String delete(WorkFullDesignchange workFullDesignchange, HttpServletRequest request,HttpServletResponse response,Model model) {
		workFullDesignchangeService.delete(workFullDesignchange);
		WorkFullDesignchange w = new WorkFullDesignchange();
		w.setWorkFullManageId(workFullDesignchange.getWorkFullManageId());
		model.addAttribute("workFullDesignchange",w);
		model.addAttribute("message","删除设计变更成功");
		return list(w,request,response,model);
	}
	/**
	 *  删除附件
	 */
	@ResponseBody
	@RequestMapping("delFile")
	public AjaxJson delFile(WorkFullDesignchange workFullDesignchange , HttpServletRequest request, Model model){
//		String attachmentFlag = request.getParameter("attachmentFlag");
//		String wtId = request.getParameter("wtId");
//		workFullDesignchange.setRemarks(wtId);
//		workFullDesignchangeService.delFile(workFullDesignchange,attachmentFlag);
//		workFullDesignchange = workFullDesignchangeService.get(workFullDesignchange.getId());
//		model.addAttribute("workFullDesignchange",workFullDesignchange);
//		return form(workFullDesignchange,model,request);
		String workFullDesignchangeId = request.getParameter("id");
		String attaId = request.getParameter("attaId");
		String attachmentUrl = request.getParameter("attachmentUrl");
		workFullDesignchange.setRemarks(attaId);
		workFullDesignchangeService.delFile(workFullDesignchange,attachmentUrl);
		AjaxJson ajaxJson = new AjaxJson();
		ajaxJson.put("attachmentUrl",attachmentUrl);
		return ajaxJson;
	}


	/**
	 * 批量删除设计变更（目前没做）
	 */
//	@RequiresPermissions("workfulldesignchange:workFullDesignchange:del")
//	@RequestMapping(value = "deleteAll")
//	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
//		String idArray[] =ids.split(",");
//		for(String id : idArray){
//			workFullDesignchangeService.delete(workFullDesignchangeService.get(id));
//		}
//		addMessage(redirectAttributes, "删除设计变更成功");
//		return "redirect:"+Global.getAdminPath()+"/workfulldesignchange/workFullDesignchange/?repage";
//	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("workfulldesignchange:workFullDesignchange:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(WorkFullDesignchange workFullDesignchange, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "设计变更"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WorkFullDesignchange> page = workFullDesignchangeService.findPage(new Page<WorkFullDesignchange>(request, response, -1), workFullDesignchange);
    		new ExportExcel("设计变更", WorkFullDesignchange.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出设计变更记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workfulldesignchange/workFullDesignchange/?repage";
    }

	/**
	 * 导入Excel数据

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

}