/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.workfullconstructsheet.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.workfullconstructsheet.entity.WorkFullConstructsheet;
import com.jeeplus.modules.workfullconstructsheet.service.WorkFullConstructsheetService;
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-06
 */
@SuppressWarnings("all")
@Controller
@RequestMapping(value = "${adminPath}/workfullconstructsheet/workFullConstructsheet")
public class WorkFullConstructsheetController extends BaseController {

	@Autowired
	private OfficeService officeService;
	@Autowired
	private ActTaskService actTaskService;
	@Autowired
	private WorkFullConstructsheetService workFullConstructsheetService;
	@Autowired
	private WorkFullManageService workFullManageService;
	@Autowired
	private ActivityService activityService;

	@ModelAttribute
	public WorkFullConstructsheet get(@RequestParam(required=false) String id) {
		WorkFullConstructsheet entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workFullConstructsheetService.get(id);
		}
		if (entity == null){
			entity = new WorkFullConstructsheet();
		}
		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 = workFullConstructsheetService.findListOfWorkFullManage(new Page<WorkFullManage>(request, response), workFullManage);
		model.addAttribute("page", page);
		return "modules/workfullconstructsheet/workfullmanageList";
	}

	/**
	 * 施工联系单列表页面
	 */
	@RequiresPermissions("workfullconstructsheet:workFullConstructsheet:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkFullConstructsheet workFullConstructsheet, HttpServletRequest request, HttpServletResponse response, Model model) {
		String workFullManageId = request.getParameter("workFullManageId");

		if(StringUtils.isNotBlank(workFullManageId)){
			workFullConstructsheet.setWorkFullManageId(workFullManageId);
		}
		Page<WorkFullConstructsheet> page = workFullConstructsheetService.findPage(new Page<WorkFullConstructsheet>(request, response), workFullConstructsheet);
		model.addAttribute("page", page);
		model.addAttribute("workFullManage",workFullManageService.get(workFullManageId));
		model.addAttribute("workFullManageId",workFullManageId);
		return "modules/workfullconstructsheet/workFullConstructsheetList";
	}

	/**
	 * 查看，增加，编辑施工联系单表单页面
	 */
	@RequiresPermissions(value={"workfullconstructsheet:workFullConstructsheet:view","workfullconstructsheet:workFullConstructsheet:add","workfullconstructsheet:workFullConstructsheet:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkFullConstructsheet workFullConstructsheet, Model model , HttpServletRequest request) {
		String dialog = request.getParameter("dialog");
		String workFullManageId = request.getParameter("workFullManageId");
		String listpage = request.getParameter("listpage");
		if(StringUtils.isBlank(workFullManageId)){
			workFullManageId = workFullConstructsheet.getWorkFullManageId();
		}
		if(StringUtils.isNotBlank(workFullManageId)){
			WorkFullManage workFullManage = workFullManageService.get(workFullManageId);
			model.addAttribute("workFullManage",workFullManage);
		}
		model.addAttribute("workFullConstructsheet", workFullConstructsheet);
		model.addAttribute("listpage",listpage);

		if(workFullConstructsheet.getAct()!=null && StringUtils.isNotBlank(workFullConstructsheet.getAct().getTaskId())){
			String taskId = workFullConstructsheet.getAct().getTaskId();
			return "modules/workfullconstructsheet/workFullConstructsheetAudit";
		}

		if("add".equals(dialog) || "edit".equals(dialog)){
			return "modules/workfullconstructsheet/workFullConstructsheetForm";
		}
		if("view".equals(dialog)){
			return "modules/workfullconstructsheet/workFullConstructsheetView";
		}

		return "modules/workfullconstructsheet/workFullConstructsheetForm";
	}

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

		model.addAttribute("processInstanceId",workFullConstructsheet.getProcessInstanceId());
		return "modules/workfullconstructsheet/workFullConstructsheetTask";
	}
	/**
	 * 待办任务
	 */
	@RequestMapping("auditTodo")
	public String auditTodo(Act act , Model model , HttpServletRequest request, HttpServletResponse response){
		act.setProcDefKey("workFullConstructsheet");
		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("db2322f3c5db4648b2306b8089a8529b",companyId);
		for (Activity activity:activities){
			act.setProcDefKey(activity.getProcessKey());
			actList.addAll(actTaskService.todoList(act));
		}
		List<WorkFullConstructsheet> constructsheetList = 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"))){
				WorkFullConstructsheet workFullConstructsheet = workFullConstructsheetService.getByProcessInstanceId(a.getProcInsId());
				if(workFullConstructsheet != null){
					workFullConstructsheet = workFullConstructsheetService.get(workFullConstructsheet.getId());
				}
				if(workFullConstructsheet != null && workFullConstructsheet.getCompanyId().equals(companyId)){
					User createBy = UserUtils.get(workFullConstructsheet.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());
								}
							}
							workFullConstructsheet.setAct(a);
							if(workFullConstructsheet.getWorkFullManage()!=null && workFullConstructsheet.getWorkFullManage().getId()!=null){
								WorkFullManage workFullManage = workFullManageService.get(workFullConstructsheet.getWorkFullManage().getId());
								workFullConstructsheet.setWorkFullManage(workFullManage);
							}
							if(StringUtils.isNotBlank(workFullConstructsheet.getId())){
								workFullConstructsheet.setName(officeService.get(companyId).getName());
							}
							constructsheetList.add(workFullConstructsheet);
						}
					}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());
							}
						}
						workFullConstructsheet.setAct(a);
						if(workFullConstructsheet.getWorkFullManage()!=null && workFullConstructsheet.getWorkFullManage().getId()!=null){
							WorkFullManage workFullManage = workFullManageService.get(workFullConstructsheet.getWorkFullManage().getId());
							workFullConstructsheet.setWorkFullManage(workFullManage);
						}
						if(StringUtils.isNotBlank(workFullConstructsheet.getId())){
							workFullConstructsheet.setName(officeService.get(companyId).getName());
						}
						constructsheetList.add(workFullConstructsheet);
					}
				}
			}
		}

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

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

		List<WorkFullConstructsheet> constructsheetList = new ArrayList<WorkFullConstructsheet>();
		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())){
				WorkFullConstructsheet workFullConstructsheet = workFullConstructsheetService.getByProcessInstanceId(a.getHistTask().getProcessInstanceId());
				if(workFullConstructsheet != null){
					workFullConstructsheet = workFullConstructsheetService.get(workFullConstructsheet.getId());
				}
				if (workFullConstructsheet != null && workFullConstructsheet.getCompanyId().equals(companyId)) {
					User createBy = UserUtils.get(workFullConstructsheet.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());
							}
							workFullConstructsheet.setAct(a);
							if(workFullConstructsheet.getWorkFullManage()!=null && workFullConstructsheet.getWorkFullManage().getId()!=null){
								WorkFullManage workFullManage = workFullManageService.get(workFullConstructsheet.getWorkFullManage().getId());
								workFullConstructsheet.setWorkFullManage(workFullManage);
							}
							if (StringUtils.isNotBlank(workFullConstructsheet.getId())){
								workFullConstructsheet.setName(officeService.get(companyId).getName());
							}
							constructsheetList.add(workFullConstructsheet);
						}
					}else {
						if (a.getVars().getMap().get("applyUserId")!=null){
							a.getVars().getMap().put("applyUserId",UserUtils.get(a.getVars().getMap().get("applyUserId").toString()).getName());
						}
						workFullConstructsheet.setAct(a);
						if(workFullConstructsheet.getWorkFullManage()!=null && workFullConstructsheet.getWorkFullManage().getId()!=null){
							WorkFullManage workFullManage = workFullManageService.get(workFullConstructsheet.getWorkFullManage().getId());
							workFullConstructsheet.setWorkFullManage(workFullManage);
						}
						if (StringUtils.isNotBlank(workFullConstructsheet.getId())){
							workFullConstructsheet.setName(officeService.get(companyId).getName());
						}
						constructsheetList.add(workFullConstructsheet);
					}
				}
			}
		}

		model.addAttribute("list", constructsheetList);
		return "modules/workfullconstructsheet/workFullConstructsheetAuditHistory";
	}

	/**
	 * 删除施工联系单
	 */
	@RequiresPermissions("workfullconstructsheet:workFullConstructsheet:del")
	@RequestMapping(value = "delete")
	public String delete(WorkFullConstructsheet workFullConstructsheet, HttpServletRequest request,HttpServletResponse response,Model model) {
		workFullConstructsheetService.delete(workFullConstructsheet);
		WorkFullConstructsheet w = new WorkFullConstructsheet();
		w.setWorkFullManageId(workFullConstructsheet.getWorkFullManageId());
		model.addAttribute("workFullConstructsheet",w);
		model.addAttribute("message","删除施工联系单成功");
		return list(w,request,response,model);
	}
	/**
	 *  删除附件
	 */
	@ResponseBody
	@RequestMapping("delFile")
	public AjaxJson delFile(WorkFullConstructsheet workFullConstructsheet , HttpServletRequest request, Model model){
//		String attachmentFlag = request.getParameter("attachmentFlag");
//		workFullConstructsheetService.delFile(workFullConstructsheet,attachmentFlag);
//		workFullConstructsheet = workFullConstructsheetService.get(workFullConstructsheet.getId());
//		model.addAttribute("workFullConstructsheet",workFullConstructsheet);
//		return form(workFullConstructsheet,model,request);
		String workFullDesignchangeId = request.getParameter("id");
		String attaId = request.getParameter("attaId");
		String attachmentUrl = request.getParameter("attachmentUrl");
		workFullConstructsheet.setRemarks(attaId);
		workFullConstructsheetService.delFile(workFullConstructsheet,attachmentUrl);
		AjaxJson ajaxJson = new AjaxJson();
		ajaxJson.put("attachmentUrl",attachmentUrl);
		return ajaxJson;
	}
	
//	/**
//	 * 批量删除施工联系单(目前没做)
//	 */
//	@RequiresPermissions("workfullconstructsheet:workFullConstructsheet:del")
//	@RequestMapping(value = "deleteAll")
//	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
//		String idArray[] =ids.split(",");
//		for(String id : idArray){
//			workFullConstructsheetService.delete(workFullConstructsheetService.get(id));
//		}
//		addMessage(redirectAttributes, "删除施工联系单成功");
//		return "redirect:"+Global.getAdminPath()+"/workfullconstructsheet/workFullConstructsheet/?repage";
//	}
//
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("workfullconstructsheet:workFullConstructsheet:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(WorkFullConstructsheet workFullConstructsheet, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "施工联系单"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WorkFullConstructsheet> page = workFullConstructsheetService.findPage(new Page<WorkFullConstructsheet>(request, response, -1), workFullConstructsheet);
    		new ExportExcel("施工联系单", WorkFullConstructsheet.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出施工联系单记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workfullconstructsheet/workFullConstructsheet/?repage";
    }

	/**
	 * 导入Excel数据

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

}