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

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.jeeplus.modules.act.entity.Act;
import com.jeeplus.modules.act.service.ActTaskService;
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.RoleActivityEnname;
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.workovertime.service.WorkOvertimeService;
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.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.workout.entity.WorkOut;
import com.jeeplus.modules.workout.service.WorkOutService;

/**
 * 出差申请Controller
 * @author ssrh
 * @version 2018-09-06
 */
@Controller
@RequestMapping(value = "${adminPath}/workout/workOut")
public class WorkOutController extends BaseController {
	@Autowired
	protected RuntimeService runtimeService;
	@Autowired
	private WorkStaffBasicInfoService workStaffBasicInfoService;
	@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 WorkOutService workOutService;
	
	@ModelAttribute
	public WorkOut get(@RequestParam(required=false) String id) {
		WorkOut entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workOutService.get(id);
		}
		if (entity == null){
			entity = new WorkOut();
		}
		return entity;
	}
	
	/**
	 * 出差申请列表页面
	 */
	@RequiresPermissions("workout:workOut:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkOut workOut, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkOut> page = workOutService.findPage(new Page<WorkOut>(request, response), workOut); 
		model.addAttribute("page", page);
		return "modules/workout/workOutList";
	}

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

		} catch (Exception e) {
			addMessage(redirectAttributes, "出差申请提交失败!");
			addMessage(redirectAttributes, "系统内部错误");
		}
		return "redirect:"+Global.getAdminPath()+"/workout/workOut/?repage";
	}

	/**
	 * 工单执行（完成任务）
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "saveAudit")
	public String saveAudit(WorkOut workOut, Model model,
							RedirectAttributes redirectAttributes) {
		try {
			List<User> users = UserUtils.getByProssType(workOut.getProcessInstanceId(),1);
			String flag = workOut.getAct().getFlag();
			if ("yes".equals(flag) && (users==null || users.size()==0)){
				addMessage(redirectAttributes, "审批失败,审批人为空,请联系管理员！");
			}else {
				String str = workOutService.auditSave(workOut,users);
				addMessage(redirectAttributes, str);
			}
		}catch (Exception e){
			addMessage(redirectAttributes, "审批失败");
		}

		if (StringUtils.isNotBlank(workOut.getHome()) && "home".equals(workOut.getHome())){
			return "redirect:" + Global.getAdminPath() + "/home/?repage";
		}else {
			return "redirect:"+Global.getAdminPath()+"/workout/workOut/?repage";
		}
	}

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

	/**
	 * 导入Excel数据

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

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