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

import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.jeeplus.common.config.Global;
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.ActTaskService;
import com.jeeplus.modules.sys.entity.MainDictDetail;
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.DictUtils;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.sysmtree.service.SysMtreeService;
import com.jeeplus.modules.workactivity.service.ActivityService;
import com.jeeplus.modules.workleave.entity.WorkLeave;
import com.jeeplus.modules.workleave.service.WorkLeaveService;
import com.jeeplus.modules.workstaff.entity.WorkStaffBasicInfo;
import com.jeeplus.modules.workstaff.service.WorkStaffBasicInfoService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
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.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 *请假
 */
@Controller
@RequestMapping(value = "${adminPath}/workleave/workLeave")
public class WorkLeaveController extends BaseController {

	@Autowired
	protected RuntimeService runtimeService;

	@Autowired
	protected TaskService taskService;

	@Autowired
	private ActTaskService actTaskService;

	@Autowired
	private HttpServletRequest request;

	@Autowired
	private SysMtreeService sysMtreeService;
	@Autowired
	private ActivityService activityService;
	@Autowired
	private OfficeService officeService;

	@Autowired
	private WorkLeaveService workLeaveService;

	@Autowired
	private WorkStaffBasicInfoService workStaffBasicInfoService;
	
	@ModelAttribute
	public WorkLeave get(@RequestParam(required=false) String id) {
		WorkLeave entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workLeaveService.get(id);
		}
		if (entity == null){
			entity = new WorkLeave();
		}
		return entity;
	}
	
	/**
	 * 申请列表页面
	 */
	@RequiresPermissions("workleave:workLeave:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkLeave workLeave, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkLeave> page = workLeaveService.findPage(new Page<WorkLeave>(request, response), workLeave);
		model.addAttribute("page", page);
		return "modules/workleave/workLeaveList";
	}

	/**
	 * 查看，增加，编辑申请表单页面
	 */
	//@RequiresPermissions(value={"workLeave:workLeave:view","workLeave:workLeave:add","workLeave:workLeave:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkLeave workLeave, Model model) {
		String view = "workLeaveForm";
		Office office = UserUtils.getSelectOffice();
		String tabId = request.getParameter("tabId");
		if("1".equals(tabId)){
			view = "workLeaveView";
		}else if("3".equals(tabId)){
			ProcessInstance processInstance = actTaskService.getProcIns(workLeave.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);
				workLeave.setAct(act);
				view = "workLeaveModify";
			}
		}
		// 环节编号
		String taskDefKey = workLeave.getAct().getTaskDefKey();
		if (StringUtils.isNotBlank(taskDefKey) && ("bmzr".equals(taskDefKey))){
			view = "workLeaveAudit";
		}
		if(StringUtils.isBlank(workLeave.getId())){
			workLeave.setName(UserUtils.getUser().getName());
			WorkStaffBasicInfo workStaffBasicInfo = new WorkStaffBasicInfo();
			workStaffBasicInfo.setUserId(UserUtils.getUser().getId());
			workStaffBasicInfo.setOffice(UserUtils.getSelectOffice());
			workStaffBasicInfo = workStaffBasicInfoService.getByUserOffice(workStaffBasicInfo);
			workLeave.setWorkStaffBasicInfo(workStaffBasicInfo);
		}
		List<MainDictDetail> cardTypes = DictUtils.getMainDictList("card_type");
		for (MainDictDetail mainDictDetail: cardTypes) {
			if (mainDictDetail.getValue().equals(workLeave.getCar())) {
				workLeave.setCar(mainDictDetail.getLabel());
				break;
			}
		}
		model.addAttribute("workLeave", workLeave);
		return "modules/workleave/"+view;
	}
	/**
	 * 暂存
	 */
	@RequestMapping(value = "store")
	public String store(WorkLeave workLeave,
                        Model model,
                        RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workLeave)){
			return form(workLeave, model);
		}
		User user = workLeave.getCreateBy();
		String submitter = "";
		if(user != null){
			submitter = user.getId();
		}
		String sta = workLeave.getStatus();
		if(!UserUtils.getUser().getId().equals(submitter) && !Strings.isNullOrEmpty(submitter) && sta != null){
			addMessage(redirectAttributes, "您不是申请人，无法修改");
			return "redirect:"+ Global.getAdminPath()+"/workleave/workLeave/?repage";
		}
		workLeave.setStatus("1"); //暂存状态
		workLeave.setCompanyId(UserUtils.getSelectCompany().getId());
		workLeave.setOfficeId(UserUtils.getSelectOffice().getId());
		if (StringUtils.isNotBlank(workLeave.getProcessInstanceId()) && workLeave.getProcessInstanceId().equals("NULL")){
			workLeave.setProcessInstanceId("");
		}
		if(!workLeave.getIsNewRecord()){//编辑表单保存
			WorkLeave t = workLeaveService.get(workLeave.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workLeave, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			workLeaveService.save(t);//保存
		}else{//新增表单保存
			workLeaveService.save(workLeave);//保存
		}
		addMessage(redirectAttributes, "保存成功");
		return "redirect:"+ Global.getAdminPath()+"/workleave/workLeave/?repage";
	}
	/**
	 * 保存申请
	 */
	@RequiresPermissions(value={"workleave:workLeave:add","workleave:workLeave:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(WorkLeave workLeave, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workLeave)){
			return form(workLeave, model);
		}
		User user = workLeave.getCreateBy();
		String sta = workLeave.getStatus();
		if(user!=null && !UserUtils.getUser().getId().equals(user.getId()) && StringUtils.isNotBlank(user.getId())){
			addMessage(redirectAttributes, "您不是申请人，无法修改");
			return "redirect:"+ Global.getAdminPath()+"/workleave/workLeave/?repage";
		}
		//状态设置为审核中
		workLeave.setStatus("2");
		String processInstanceId ="";
		if (user!=null && StringUtils.isNotBlank(user.getId()) && StringUtils.isNotBlank(sta) && "3".equals(sta)){
			processInstanceId = workLeaveService.get(workLeave.getId()).getProcessInstanceId();
		}
//		try {
			Map<String, Object> variables = Maps.newHashMap();
			workLeave.setCompanyId(UserUtils.getSelectCompany().getId());
			workLeave.setOfficeId(UserUtils.getSelectOffice().getId());
			String str = workLeaveService.save(workLeave, variables,processInstanceId);
			if (StringUtils.isNotBlank(str)){
				addMessage(redirectAttributes, "申请提交失败:"+str);
			}else {
				addMessage(redirectAttributes, "申请已经提交");
			}

//		} catch (Exception e) {
//			addMessage(redirectAttributes, "申请提交失败!");
//			addMessage(redirectAttributes, "系统内部错误");
//		}
		return "redirect:"+ Global.getAdminPath()+"/workleave/workLeave/?repage";
	}
	/**
	 * 工单执行（完成任务）
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "saveAudit")
	public String saveAudit(WorkLeave workLeave, Model model,
                            RedirectAttributes redirectAttributes) {
		try {
            // 对不同环节的业务逻辑进行操作
            String taskDefKey = workLeave.getAct().getTaskDefKey();
            List<User> users = null;
            if ("bmzr".equals(taskDefKey)){
                users = UserUtils.getByProssType(workLeave.getProcessInstanceId(),2);
                if (users==null )
                    users = UserUtils.getByRoleActivityEnname("fzjl",3,workLeave.getOfficeId(),"25",workLeave.getCreateBy());
            }else  if ("fgld".equals(taskDefKey)){
                users = UserUtils.getByProssType(workLeave.getProcessInstanceId(),3);
                if (users==null )
                    users = UserUtils.getByRoleActivityEnname("zjl", 3, workLeave.getOfficeId(), "25", workLeave.getCreateBy());
            }else  if ("zjl".equals(taskDefKey)){
                users = UserUtils.getByProssType(workLeave.getProcessInstanceId(),3);
                if (users==null )
                    users = UserUtils.getByRoleActivityEnname("zjl", 3, workLeave.getOfficeId(), "25", workLeave.getCreateBy());
            }else if ("modifyApply".equals(taskDefKey)){
                users = UserUtils.getByProssType(workLeave.getProcessInstanceId(),1);
                if (users==null )
                    users = UserUtils.getByRoleActivityEnname("bmzr",3,workLeave.getOfficeId(),"25",workLeave.getCreateBy());
            }
            if (users==null || (users==null || users.size()==0)){
                addMessage(redirectAttributes, "审批失败,审批人为空,请联系管理员！");
            }else {
                String str = workLeaveService.auditSave(workLeave,users);
                addMessage(redirectAttributes, str);
            }
		}catch (Exception e){
			addMessage(redirectAttributes, "审批失败");
		}

		if (StringUtils.isNotBlank(workLeave.getHome()) && "home".equals(workLeave.getHome())){
			return "redirect:" + Global.getAdminPath() + "/home/?repage";
		}else {
			return "redirect:"+ Global.getAdminPath()+"/workleave/workLeave/?repage";
		}
	}
	/**
	 * 删除加班申请
	 */
	@RequiresPermissions("workleave:workLeave:del")
	@RequestMapping(value = "delete")
	public String delete(WorkLeave workLeave, RedirectAttributes redirectAttributes) {
		workLeaveService.delete(workLeave);
		addMessage(redirectAttributes, "删除申请成功");
		return "redirect:"+ Global.getAdminPath()+"/workleave/workLeave/?repage";
	}
	


	/**
	 * 强制撤销
	 */
	@RequestMapping("cancelInvalidate")
	public String cancelInvalidate(WorkLeave workLeave, RedirectAttributes redirectAttributes){
		workLeaveService.cancelInvalidate(workLeave);
		return "redirect:"+ Global.getAdminPath()+"/workleave/workLeave/?repage";
	}
	/**
	 * 读取单个实体流程
	 * @return
	 */
	@RequestMapping(value = "getProcessOne")
	public String getProcessOne(WorkLeave workLeave, Model model) {
		model.addAttribute("processInstanceId", workLeave.getProcessInstanceId());
		return "modules/workleave/workTrack";
	}
	

}