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

import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.utils.MyBeanUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.modules.act.entity.Act;
import com.jeeplus.modules.act.service.ActAuditService;
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.User;
import com.jeeplus.modules.sys.service.OfficeService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workgoout.entity.GoOut;
import com.jeeplus.modules.workgoout.service.GoOutService;
import com.jeeplus.modules.workprojectnotify.entity.WorkProjectNotify;
import com.jeeplus.modules.workprojectnotify.service.WorkProjectNotifyService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 外出流程Controller
 * @author LXH
 * @version 2017-07-05
 */
@Controller
@RequestMapping(value = "${adminPath}/goout/goOut")
public class GoOutController extends BaseController {

	@Autowired
	private GoOutService goOutService;

	private Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	protected RuntimeService runtimeService;

	@Autowired
	protected TaskService taskService;

	@Autowired
	private ActTaskService actTaskService;
	@Autowired
	private WorkProjectNotifyService workProjectNotifyService;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private ActAuditService actAuditService;

	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


	@ModelAttribute
	public GoOut get(@RequestParam(required=false) String id) {
		GoOut entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = goOutService.get(id);
		}
		if (entity == null){
			entity = new GoOut();
		}
		return entity;
	}

	@RequiresPermissions(value={"goout:goOut:view","goout:goOut:add","goout:goOut:edit"},logical= Logical.OR)
	@RequestMapping(value = {"form"})
	public String form(GoOut entity, Model model) {
		String view = "goOutForm";
		// 查看审批申请单
		if (org.apache.commons.lang3.StringUtils.isNotBlank(entity.getId())){//.getAct().getProcInsId())){
			// 环节编号
			String taskDefKey = entity.getAct().getTaskDefKey();
			if (taskDefKey!=null) {
				// 查看工单
				if (entity.getAct().isFinishTask()) {
					view = "goOutView";
				}
				// 修改环节
				else if ("apply_end".equals(taskDefKey)) {
					view = "goOutAudit";
				}
				// 审核环节
				else if ("audit1".equals(taskDefKey)) {
					if (org.apache.commons.lang3.StringUtils.isBlank(entity.getAct().getStatus())){
						model.addAttribute("disabled","true");
					}else {
						model.addAttribute("disabled","false");
					}
					view = "goOutAudit";
				}
				//
				else if ("modifyApply".equals(taskDefKey)) {
					view = "goOutForm";
				}
			}
			if (org.apache.commons.lang3.StringUtils.isNotBlank(entity.getName())){
				if (entity.getName().equals("view")){
					model.addAttribute("disabled","true");
					entity.getAct().setProcInsId(entity.getProcessInstanceId());
					view = "goOutAudit";
				}
			}
		}

		model.addAttribute("goOut", entity);
		return "modules/goout/"+view;
	}

	/**
	 * 启动外出流程
	 * @param entity
	 */
	@RequestMapping(value = "save", method = RequestMethod.POST)
	public String save(GoOut entity, @RequestParam(value = "this_upload_files",required = false)MultipartFile[] this_upload_files, RedirectAttributes redirectAttributes) throws Exception{
		if (org.apache.commons.lang3.StringUtils.isNotBlank(entity.getId())) {
			GoOut t = goOutService.get(entity.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(entity, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			if (t.getStatus().equals("3") || t.getStatus().equals("4")){
				addMessage(redirectAttributes, "已结束流程不能修改！");
			}else {
				goOutService.save(t);
			}
		} else {
			try {
				boolean b = goOutService.saveGoOut(entity,this_upload_files);
				if (b){
					addMessage(redirectAttributes, "外出申请已经提交");
				}else {
					addMessage(redirectAttributes, "系统内部错误！");
				}
			}catch (Exception e){
				logger.info("save e.getMessage()="+e.getMessage());
				addMessage(redirectAttributes, "系统内部错误！");
			}
		}
		return "redirect:"+ Global.getAdminPath()+"/goout/goOut/?repage";
	}


	/**
	 * 工单执行（完成任务）
	 * @param goOut
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "saveAudit")
	public String saveAudit(GoOut goOut, Map<String, Object> vars, Model model, RedirectAttributes redirectAttributes) {
		/*if (org.apache.commons.lang3.StringUtils.isBlank(goOut.getAct().getComment())){
			addMessage(model, "请填写审核意见。");
			return form(goOut, model);
		}*/
		//goOutService.auditSave(goOut);
		Act act = goOut.getAct();
		AjaxJson json = actAuditService.saveAudit(act, act.getProcInsId(), "goout", goOut.getAct().getComment(), goOut.getId(), "2");
		addMessage(redirectAttributes, json.getMsg());
		if (goOut!=null && org.apache.commons.lang3.StringUtils.isNotBlank(goOut.getHome()) && goOut.getHome().equals("home")){
			return "redirect:" + adminPath + "/home";
		}
		return "redirect:" + adminPath + "/goout/goOut";
	}

	/**
	 * 读取所有流程
	 * @return
	 */
	@RequiresPermissions("goout:goOut:list")
	@RequestMapping(value = {"list", ""})
	public String list(GoOut goOut, HttpServletRequest request, HttpServletResponse response, Model model) {
		User user = UserUtils.getUser();
		if (!user.isAdmin()){
			goOut.setCompanyId(user.getComId());
			if (!UserUtils.isManager()){
				goOut.setCreateBy(user);
			}
		}
		Page<GoOut> page = goOutService.find(new Page<GoOut>(request, response), goOut);
		model.addAttribute("page", page);
		return "modules/goout/goOutList";
	}

	/**
	 * 待办任务列表页面
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = {"goOutTodoList"})
	public String goOutTodoList(Act act, HttpServletRequest request, HttpServletResponse response, Model model) {
		act.setProcDefKey("goout");
		List<Act> list = actTaskService.todoList(act);
		Office office = UserUtils.getSelectCompany();
		String companyId = office==null?"":office.getId();
		List<GoOut> lists = new ArrayList<GoOut>();
		for (Act a : list) {
			GoOut goOut = goOutService.getByProcessInstanceId(a.getProcInsId());
			if (goOut != null && goOut.getCompanyId().equals(companyId)) {
				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());
					}
				}
				goOut.setAct(a);
				if (com.jeeplus.common.utils.StringUtils.isNotBlank(goOut.getId())){
					goOut.setName(officeService.get(companyId).getName());
				}
				lists.add(goOut);
			}
		}
		model.addAttribute("list", lists);
		return "modules/goout/goOutTodoList";
	}

	/**
	 * 已办任务
	 * @param act
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = {"goOutHistoricList"})
	public String goOutHistoricList (Act act, HttpServletRequest request, HttpServletResponse response, Model model){
		act.setProcDefKey("goout");
		Page<Act> page = actTaskService.historicList(new Page<Act>(request, response), act);
		List<Act> list = page.getList();
		Office office = UserUtils.getSelectCompany();
		String companyId = office==null?"":office.getId();
		List<GoOut> lists = new ArrayList<GoOut>();
		for (Act a : list) {
			GoOut goOut = goOutService.getByProcessInstanceId(a.getHistTask().getProcessInstanceId());
			if (goOut != null && goOut.getCompanyId().equals(companyId)) {
				if (a.getVars().getMap().get("applyUserId")!=null){
					a.getVars().getMap().put("applyUserId",UserUtils.get(a.getVars().getMap().get("applyUserId").toString()).getName());
				}
				goOut.setAct(a);
				if (com.jeeplus.common.utils.StringUtils.isNotBlank(goOut.getId())){
					goOut.setName(officeService.get(companyId).getName());
				}
				lists.add(goOut);
			}
		}
		model.addAttribute("list", lists);

		return "modules/goout/goOutHistoricList";
	}

	/**
	 * 审核企业信息
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "applyOnGoOut")
	public String applyOnCompany(Act act, HttpServletResponse response, Model model) {
		// 获取流程XML上的表单KEY
		String formKey = actTaskService.getFormKey(act.getProcDefId(), act.getTaskDefKey());
		//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);
	}

	/**
	 * 外出申请撤销
	 * @param
	 * @return
	 */
	@RequestMapping(value = "revoke")
	public String revoke(HttpServletRequest request, HttpServletResponse response) {

		HashMap<String, String> requestMap = findRequestMap(request);
		String processInstanceId = requestMap.get("processInstanceId");
		String id = requestMap.get("id");
		String deleteReason = requestMap.get("gooutReason");

		AjaxJson j = new AjaxJson();
		try {
			GoOut out = goOutService.getById(id);
			out.setStatus("5");
			out.preUpdate();
			goOutService.update(out);
			Map map = goOutService.getGoOutById(id, "1");
			j.put("data",map);
			actTaskService.endProcessInstance(processInstanceId, deleteReason);
			j.setMsg("撤销申请成功");

			//撤销后，更改所有发送过的通知的阅读状态
			WorkProjectNotify notify = new WorkProjectNotify();
			notify.setNotifyId(out.getId());
			workProjectNotifyService.readByNotifyId(notify);
		}catch (Exception e){
			j.setErrorCode("101");
			logger.info(e.getMessage());
			j.setMsg("撤销申请失败");
			j.setSuccess(false);
		}
		return "redirect:" + adminPath + "/goout/goOut";
	}
}